signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __bounce(self, **kwargs):
start_point = kwargs.pop('<STR_LIT>')<EOL>hit_point = kwargs.pop('<STR_LIT>')<EOL>end_point = kwargs.pop('<STR_LIT>')<EOL>feature = kwargs.pop('<STR_LIT>')<EOL>distance = kwargs.pop('<STR_LIT>')<EOL>angle = kwargs.pop('<STR_LIT>')<EOL>points_in_shore = [Point(x) for x in list(feature.coords)]<EOL>points_in_shore = sorted(points_in_shore, key=lambda x: x.x)<EOL>first_shore = points_in_shore[<NUM_LIT:0>]<EOL>last_shore = points_in_shore[-<NUM_LIT:1>]<EOL>shoreline_x = abs(abs(first_shore.x) - abs(last_shore.x))<EOL>shoreline_y = abs(abs(first_shore.y) - abs(last_shore.y))<EOL>beta = math.degrees(math.atan(shoreline_x / shoreline_y))<EOL>theta = <NUM_LIT> - angle - beta<EOL>bounce_azimuth = AsaMath.math_angle_to_azimuth(angle=<NUM_LIT:2> * theta + angle)<EOL>print("<STR_LIT>" + str(beta))<EOL>print("<STR_LIT>" + str(angle))<EOL>print("<STR_LIT>" + str(theta + angle))<EOL>print("<STR_LIT>" + str(bounce_azimuth))<EOL>print("<STR_LIT>" + str(AsaMath.azimuth_to_math_angle(azimuth=bounce_azimuth)))<EOL>after_distance = distance - AsaGreatCircle.great_distance(start_point=start_point, end_point=hit_point)['<STR_LIT>']<EOL>new_point = AsaGreatCircle.great_circle(distance=after_distance, azimuth=bounce_azimuth, start_point=hit_point)<EOL>return Location4D(latitude=new_point['<STR_LIT>'], longitude=new_point['<STR_LIT>'], depth=start_point.depth)<EOL>
Bounce off of the shoreline. NOTE: This does not work, but left here for future implementation feature = Linestring of two points, being the line segment the particle hit. angle = decimal degrees from 0 (x-axis), couter-clockwise (math style)
f3628:c0:m11
def __reverse(self, **kwargs):
start_point = kwargs.pop('<STR_LIT>')<EOL>hit_point = kwargs.pop('<STR_LIT>')<EOL>distance = kwargs.pop('<STR_LIT>')<EOL>azimuth = kwargs.pop('<STR_LIT>')<EOL>reverse_azimuth = kwargs.pop('<STR_LIT>')<EOL>reverse_distance = kwargs.get('<STR_LIT>', None)<EOL>if reverse_distance is None:<EOL><INDENT>reverse_distance = <NUM_LIT:100><EOL><DEDENT>random_azimuth = reverse_azimuth + AsaRandom.random() * <NUM_LIT:5><EOL>count = <NUM_LIT:0><EOL>nudge_distance = <NUM_LIT><EOL>nudge_point = AsaGreatCircle.great_circle(distance=nudge_distance, azimuth=reverse_azimuth, start_point=hit_point)<EOL>nudge_loc = Location4D(latitude=nudge_point['<STR_LIT>'], longitude=nudge_point['<STR_LIT>'], depth=start_point.depth)<EOL>while self.intersect(single_point=nudge_loc.point) and count < <NUM_LIT:16>:<EOL><INDENT>nudge_distance *= <NUM_LIT:2><EOL>nudge_point = AsaGreatCircle.great_circle(distance=nudge_distance, azimuth=reverse_azimuth, start_point=hit_point)<EOL>nudge_loc = Location4D(latitude=nudge_point['<STR_LIT>'], longitude=nudge_point['<STR_LIT>'], depth=start_point.depth)<EOL>count += <NUM_LIT:1><EOL><DEDENT>if count == <NUM_LIT:16>:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return start_point<EOL><DEDENT>count = <NUM_LIT:0><EOL>changing_distance = reverse_distance<EOL>new_point = AsaGreatCircle.great_circle(distance=reverse_distance, azimuth=random_azimuth, start_point=hit_point)<EOL>new_loc = Location4D(latitude=new_point['<STR_LIT>'], longitude=new_point['<STR_LIT>'], depth=start_point.depth)<EOL>while self.intersect(start_point=nudge_loc.point, end_point=new_loc.point) and count < <NUM_LIT:12>:<EOL><INDENT>changing_distance /= <NUM_LIT:2><EOL>new_point = AsaGreatCircle.great_circle(distance=changing_distance, azimuth=random_azimuth, start_point=hit_point)<EOL>new_loc = Location4D(latitude=new_point['<STR_LIT>'], longitude=new_point['<STR_LIT>'], depth=start_point.depth)<EOL>count += <NUM_LIT:1><EOL><DEDENT>if count == <NUM_LIT:12>:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>return start_point<EOL><DEDENT>return new_loc<EOL>
Reverse particle just off of the shore in the direction that it came in. Adds a slight random factor to the distance and angle it is reversed in.
f3628:c0:m12
def __init__(self, file=None, path=None, **kwargs):
if path is not None:<EOL><INDENT>self._file = os.path.normpath(path)<EOL><DEDENT>elif file is not None:<EOL><INDENT>self._file = os.path.normpath(file)<EOL><DEDENT>else:<EOL><INDENT>self._file = os.path.normpath(os.path.join(__file__,"<STR_LIT>"))<EOL><DEDENT>self._source = ogr.Open(self._file, GA_ReadOnly)<EOL>if not self._source:<EOL><INDENT>raise Exception('<STR_LIT>'.format(self._file))<EOL><DEDENT>self._layer = self._source.GetLayer()<EOL>super(ShorelineFile, self).__init__(**kwargs)<EOL>
Optional named arguments: * file (local path to OGC complient file) * path (used instead of file) MUST BE land polygons!!
f3628:c1:m0
def get_capabilities(self):
d = {}<EOL>ext = self._layer.GetExtent() <EOL>llbb = [round(float(v), <NUM_LIT:4>) for v in ext]<EOL>d['<STR_LIT>'] = box(llbb[<NUM_LIT:0>], llbb[<NUM_LIT:2>], llbb[<NUM_LIT:1>], llbb[<NUM_LIT:3>])<EOL>d['<STR_LIT:Name>'] = self._file.split('<STR_LIT:/>')[-<NUM_LIT:1>].split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>return d<EOL>
Gets capabilities. This is a simulation of a GetCapabilities WFS request. Returns a python dict with LatLongBoundingBox and Name keys defined.
f3628:c1:m2
def get_feature_type_info(self):
return self.get_capabilities()<EOL>
Gets FeatureType as a python dict. On ShorelineFile this is a passthrough to the simulated get_capabilities.
f3628:c1:m3
def get_geoms_for_bounds(self, bounds):
poly = ogr.CreateGeometryFromWkt(bounds)<EOL>self._layer.SetSpatialFilter(poly)<EOL>poly.Destroy()<EOL>return [json.loads(e.GetGeometryRef().ExportToJson()) for e in self._layer]<EOL>
Helper method to get geometries within a certain bounds (as WKT). Returns GeoJSON (loaded as a list of python dictionaries).
f3628:c1:m4
def index(self, point=None, spatialbuffer=None):
spatialbuffer = spatialbuffer or self._spatialbuffer<EOL>self._layer.SetSpatialFilter(None)<EOL>self._spatial_query_object = None<EOL>geoms = []<EOL>if point:<EOL><INDENT>self._spatial_query_object = point.buffer(spatialbuffer)<EOL>geoms = self.get_geoms_for_bounds(self._spatial_query_object.wkt)<EOL><DEDENT>self._geoms = []<EOL>for element in geoms:<EOL><INDENT>try:<EOL><INDENT>geom = asShape(element)<EOL>if isinstance(geom, Polygon):<EOL><INDENT>self._geoms.append(geom)<EOL><DEDENT>elif isinstance(geom, MultiPolygon):<EOL><INDENT>for poly in geom:<EOL><INDENT>self._geoms.append(poly)<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>logger.warn("<STR_LIT>" % (str(point), str(spatialbuffer)))<EOL><DEDENT><DEDENT>
This queries the shapefile around a buffer of a point The results of this spatial query are used for shoreline detection. Using the entire shapefile without the spatial query takes over 30 times the time with world land polygons.
f3628:c1:m5
def get_capabilities(self):
params = {'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT:version>' : '<STR_LIT>'}<EOL>caps_response = requests.get(self._wfs_server, params=params)<EOL>caps_response.raise_for_status()<EOL>return ET.fromstring(caps_response.content)<EOL>
Gets capabilities. Queries WFS server for its capabilities. Internally used by get_feature_type_info.
f3628:c2:m1
def get_feature_type_info(self):
caps = self.get_capabilities()<EOL>if caps is None:<EOL><INDENT>return None<EOL><DEDENT>el = caps.find('<STR_LIT>')<EOL>for e in el.findall('<STR_LIT>'):<EOL><INDENT>if e.find('<STR_LIT>').text == self._feature_name:<EOL><INDENT>d = {sube.tag[<NUM_LIT>:]:sube.text or sube.attrib or None for sube in e.getchildren()}<EOL>llbb = {k:round(float(v), <NUM_LIT:4>) for k,v in d['<STR_LIT>'].items()}<EOL>d['<STR_LIT>'] = box(llbb['<STR_LIT>'], llbb['<STR_LIT>'], llbb['<STR_LIT>'], llbb['<STR_LIT>'])<EOL>return d<EOL><DEDENT><DEDENT>return None<EOL>
Gets FeatureType as a python dict. Transforms feature_name info into python dict.
f3628:c2:m2
def get_geoms_for_bounds(self, bounds):
params = {'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : self._feature_name,<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT:version>' : '<STR_LIT>',<EOL>'<STR_LIT>' : '<STR_LIT:U+002C>'.join((str(b) for b in wkt.loads(bounds).bounds))}<EOL>raw_geojson_response = requests.get(self._wfs_server, params=params)<EOL>raw_geojson_response.raise_for_status()<EOL>geojson = raw_geojson_response.json()<EOL>return [g['<STR_LIT>'] for g in geojson['<STR_LIT>']]<EOL>
Helper method to get geometries within a certain bounds (as WKT). Returns GeoJSON (loaded as a list of python dictionaries).
f3628:c2:m3
def __init__(self, task_queue, result_queue, n_run, nproc_lock, active, get_data, **kwargs):
multiprocessing.Process.__init__(self, **kwargs)<EOL>self.task_queue = task_queue<EOL>self.result_queue = result_queue<EOL>self.n_run = n_run<EOL>self.nproc_lock = nproc_lock<EOL>self.active = active<EOL>self.get_data = get_data<EOL>
This is the process class that does all the handling of queued tasks
f3630:c0:m0
def __init__(self, hydrodataset, common_variables, n_run, get_data, write_lock, has_write_lock, read_lock, read_count,<EOL>time_chunk, horiz_chunk, times, start_time, point_get, start, **kwargs):
assert "<STR_LIT>" in kwargs<EOL>self.cache_path = kwargs["<STR_LIT>"]<EOL>self.caching = kwargs.get("<STR_LIT>", True)<EOL>self.hydrodataset = hydrodataset<EOL>if self.cache_path == self.hydrodataset and self.caching is True:<EOL><INDENT>raise DataControllerError("<STR_LIT>")<EOL><DEDENT>self.n_run = n_run<EOL>self.get_data = get_data<EOL>self.write_lock = write_lock<EOL>self.has_write_lock = has_write_lock<EOL>self.read_lock = read_lock<EOL>self.read_count = read_count<EOL>self.inds = None <EOL>self.time_size = time_chunk<EOL>self.horiz_size = horiz_chunk<EOL>self.point_get = point_get<EOL>self.start_time = start_time<EOL>self.times = times<EOL>self.start = start<EOL>self.uname = common_variables.get("<STR_LIT:u>", None)<EOL>self.vname = common_variables.get("<STR_LIT:v>", None)<EOL>self.wname = common_variables.get("<STR_LIT:w>", None)<EOL>self.temp_name = common_variables.get("<STR_LIT>", None)<EOL>self.salt_name = common_variables.get("<STR_LIT>", None)<EOL>self.xname = common_variables.get("<STR_LIT:x>", None)<EOL>self.yname = common_variables.get("<STR_LIT:y>", None)<EOL>self.zname = common_variables.get("<STR_LIT:z>", None)<EOL>self.tname = common_variables.get("<STR_LIT:time>", None)<EOL>
The data controller controls the updating of the local netcdf data cache
f3630:c1:m0
def get_remote_data(self, localvars, remotevars, inds, shape):
<EOL>if self.horiz_size == '<STR_LIT:all>':<EOL><INDENT>y, y_1 = <NUM_LIT:0>, shape[-<NUM_LIT:2>]<EOL>x, x_1 = <NUM_LIT:0>, shape[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>r = self.horiz_size<EOL>x, x_1 = self.point_get.value[<NUM_LIT:2>]-r, self.point_get.value[<NUM_LIT:2>]+r+<NUM_LIT:1><EOL>y, y_1 = self.point_get.value[<NUM_LIT:1>]-r, self.point_get.value[<NUM_LIT:1>]+r+<NUM_LIT:1><EOL>x, x_1 = x[<NUM_LIT:0>], x_1[<NUM_LIT:0>]<EOL>y, y_1 = y[<NUM_LIT:0>], y_1[<NUM_LIT:0>]<EOL>if y < <NUM_LIT:0>:<EOL><INDENT>y = <NUM_LIT:0><EOL><DEDENT>if x < <NUM_LIT:0>:<EOL><INDENT>x = <NUM_LIT:0><EOL><DEDENT>if y_1 > shape[-<NUM_LIT:2>]:<EOL><INDENT>y_1 = shape[-<NUM_LIT:2>]<EOL><DEDENT>if x_1 > shape[-<NUM_LIT:1>]:<EOL><INDENT>x_1 = shape[-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>domain = self.local.variables['<STR_LIT>']<EOL>if len(shape) == <NUM_LIT:4>:<EOL><INDENT>domain[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, <NUM_LIT:0>:shape[<NUM_LIT:1>], y:y_1, x:x_1] = np.ones((inds[-<NUM_LIT:1>]+<NUM_LIT:1>-inds[<NUM_LIT:0>], shape[<NUM_LIT:1>], y_1-y, x_1-x))<EOL><DEDENT>elif len(shape) == <NUM_LIT:3>:<EOL><INDENT>domain[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, y:y_1, x:x_1] = np.ones((inds[-<NUM_LIT:1>]+<NUM_LIT:1>-inds[<NUM_LIT:0>], y_1-y, x_1-x))<EOL><DEDENT>logger.debug("<STR_LIT>" % (str(inds[<NUM_LIT:0>]), str(inds[-<NUM_LIT:1>]+<NUM_LIT:1>), str(y), str(y_1), str(x), str(x_1)))<EOL>for local, remote in zip(localvars, remotevars):<EOL><INDENT>if len(shape) == <NUM_LIT:4>:<EOL><INDENT>local[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, <NUM_LIT:0>:shape[<NUM_LIT:1>], y:y_1, x:x_1] = remote[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, <NUM_LIT:0>:shape[<NUM_LIT:1>], y:y_1, x:x_1]<EOL><DEDENT>else:<EOL><INDENT>local[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, y:y_1, x:x_1] = remote[inds[<NUM_LIT:0>]:inds[-<NUM_LIT:1>]+<NUM_LIT:1>, y:y_1, x:x_1]<EOL><DEDENT><DEDENT>
Method that does the updating of local netcdf cache with remote data
f3630:c1:m1
def __init__(self, hydrodataset, part, common_variables, timevar, times, start_time, models,<EOL>release_location_centroid, usebathy, useshore, usesurface,<EOL>get_data, n_run, read_lock, has_read_lock, read_count,<EOL>point_get, data_request_lock, has_data_request_lock, reverse_distance=None, bathy=None,<EOL>shoreline_path=None, shoreline_feature=None, time_method=None, caching=None):
assert "<STR_LIT>" is not None<EOL>self.hydrodataset = hydrodataset<EOL>self.bathy = bathy<EOL>self.common_variables = common_variables<EOL>self.release_location_centroid = release_location_centroid<EOL>self.part = part<EOL>self.times = times<EOL>self.start_time = start_time<EOL>self.models = models<EOL>self.usebathy = usebathy<EOL>self.useshore = useshore<EOL>self.usesurface = usesurface<EOL>self.get_data = get_data<EOL>self.n_run = n_run<EOL>self.read_lock = read_lock<EOL>self.has_read_lock = has_read_lock<EOL>self.read_count = read_count<EOL>self.point_get = point_get<EOL>self.data_request_lock = data_request_lock<EOL>self.has_data_request_lock = has_data_request_lock<EOL>self.shoreline_path = shoreline_path<EOL>self.shoreline_feature = shoreline_feature<EOL>self.timevar = timevar<EOL>if caching is None:<EOL><INDENT>caching = True<EOL><DEDENT>self.caching = caching<EOL>self.uname = common_variables.get("<STR_LIT:u>", None)<EOL>self.vname = common_variables.get("<STR_LIT:v>", None)<EOL>self.wname = common_variables.get("<STR_LIT:w>", None)<EOL>self.temp_name = common_variables.get("<STR_LIT>", None)<EOL>self.salt_name = common_variables.get("<STR_LIT>", None)<EOL>self.xname = common_variables.get("<STR_LIT:x>", None)<EOL>self.yname = common_variables.get("<STR_LIT:y>", None)<EOL>self.zname = common_variables.get("<STR_LIT:z>", None)<EOL>self.tname = common_variables.get("<STR_LIT:time>", None)<EOL>self.reverse_distance = reverse_distance<EOL>if time_method is None:<EOL><INDENT>time_method = '<STR_LIT>'<EOL><DEDENT>self.time_method = time_method<EOL>
This is the task/class/object/job that forces an individual particle and communicates with the other particles and data controller for local cache updates
f3630:c2:m1
def need_data(self, i):
<EOL>if self.caching is False:<EOL><INDENT>return False<EOL><DEDENT>logger.debug("<STR_LIT>" % self.part.location.logstring())<EOL>try:<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT>self.dataset.opennc()<EOL>cached_lookup = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location)<EOL>logger.debug("<STR_LIT>" % type(cached_lookup))<EOL>logger.debug("<STR_LIT>" % np.mean(np.mean(cached_lookup)))<EOL>logger.debug("<STR_LIT>" % type(np.mean(np.mean(cached_lookup))))<EOL>if type(np.mean(np.mean(cached_lookup))) == np.ma.core.MaskedConstant:<EOL><INDENT>need = True<EOL>logger.debug("<STR_LIT>" % cached_lookup)<EOL><DEDENT>else:<EOL><INDENT>need = False<EOL>logger.debug("<STR_LIT>")<EOL><DEDENT><DEDENT>except StandardError:<EOL><INDENT>need = True<EOL>logger.debug("<STR_LIT>")<EOL><DEDENT>finally:<EOL><INDENT>self.dataset.closenc()<EOL>with self.read_lock:<EOL><INDENT>self.read_count.value -= <NUM_LIT:1><EOL>self.has_read_lock.remove(os.getpid())<EOL><DEDENT><DEDENT>return need<EOL>
Method to test if cache contains the data that the particle needs
f3630:c2:m2
def linterp(self, setx, sety, x):
if math.isnan(sety[<NUM_LIT:0>]) or math.isnan(setx[<NUM_LIT:0>]):<EOL><INDENT>return np.nan<EOL><DEDENT>return sety[<NUM_LIT:0>] + (x - setx[<NUM_LIT:0>]) * ( (sety[<NUM_LIT:1>]-sety[<NUM_LIT:0>]) / (setx[<NUM_LIT:1>]-setx[<NUM_LIT:0>]) )<EOL>
Linear interp of model data values between time steps
f3630:c2:m3
def data_interp(self, i, currenttime):
if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT>if self.need_data(i+<NUM_LIT:1>):<EOL><INDENT>self.data_request_lock.acquire()<EOL>self.has_data_request_lock.value = os.getpid()<EOL>try:<EOL><INDENT>if self.need_data(i+<NUM_LIT:1>):<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT>self.dataset.opennc()<EOL>indices = self.dataset.get_indices('<STR_LIT:u>', timeinds=[np.asarray([i-<NUM_LIT:1>])], point=self.part.location )<EOL>self.dataset.closenc()<EOL>with self.read_lock:<EOL><INDENT>self.read_count.value -= <NUM_LIT:1><EOL>self.has_read_lock.remove(os.getpid())<EOL><DEDENT>self.point_get.value = [indices[<NUM_LIT:0>] + <NUM_LIT:1>, indices[-<NUM_LIT:2>], indices[-<NUM_LIT:1>]]<EOL>self.get_data.value = True<EOL>if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT>if self.need_data(i+<NUM_LIT:1>):<EOL><INDENT>self.point_get.value = [indices[<NUM_LIT:0>] + <NUM_LIT:2>, indices[-<NUM_LIT:2>], indices[-<NUM_LIT:1>]]<EOL>self.get_data.value = True<EOL>if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except StandardError:<EOL><INDENT>logger.warn("<STR_LIT>")<EOL>raise<EOL><DEDENT>finally:<EOL><INDENT>self.has_data_request_lock.value = -<NUM_LIT:1><EOL>self.data_request_lock.release()<EOL><DEDENT><DEDENT>if self.caching is True:<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT><DEDENT>try:<EOL><INDENT>self.dataset.opennc()<EOL>u = [np.mean(np.mean(self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i])], point=self.part.location ))),<EOL>np.mean(np.mean(self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location )))]<EOL>v = [np.mean(np.mean(self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i])], point=self.part.location ))),<EOL>np.mean(np.mean(self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location )))]<EOL>if '<STR_LIT:w>' in self.dataset.nc.variables:<EOL><INDENT>w = [np.mean(np.mean(self.dataset.get_values('<STR_LIT:w>', timeinds=[np.asarray([i])], point=self.part.location ))),<EOL>np.mean(np.mean(self.dataset.get_values('<STR_LIT:w>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location )))]<EOL><DEDENT>else:<EOL><INDENT>w = [<NUM_LIT:0.0>, <NUM_LIT:0.0>]<EOL><DEDENT>if self.temp_name is not None and self.salt_name is not None:<EOL><INDENT>temp = [np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location ))),<EOL>np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location )))]<EOL>salt = [np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location ))),<EOL>np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location )))]<EOL><DEDENT>if np.isnan(u).any() or np.isnan(v).any() or np.isnan(w).any():<EOL><INDENT>uarray1 = self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>varray1 = self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>uarray2 = self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location, num=<NUM_LIT:2>)<EOL>varray2 = self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location, num=<NUM_LIT:2>)<EOL>if '<STR_LIT:w>' in self.dataset.nc.variables:<EOL><INDENT>warray1 = self.dataset.get_values('<STR_LIT:w>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>warray2 = self.dataset.get_values('<STR_LIT:w>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location, num=<NUM_LIT:2>)<EOL>w = [warray1.mean(), warray2.mean()]<EOL><DEDENT>else:<EOL><INDENT>w = [<NUM_LIT:0.0>, <NUM_LIT:0.0>]<EOL><DEDENT>if self.temp_name is not None and self.salt_name is not None:<EOL><INDENT>temparray1 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>saltarray1 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>temparray2 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location, num=<NUM_LIT:2>)<EOL>saltarray2 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i+<NUM_LIT:1>])], point=self.part.location, num=<NUM_LIT:2>)<EOL>temp = [temparray1.mean(), temparray2.mean()]<EOL>salt = [saltarray1.mean(), saltarray2.mean()]<EOL><DEDENT>u = [uarray1.mean(), uarray2.mean()]<EOL>v = [varray1.mean(), varray2.mean()]<EOL><DEDENT>currenttime = date2num(currenttime)<EOL>timevar = self.timevar.datenum<EOL>u = self.linterp(timevar[i:i+<NUM_LIT:2>], u, currenttime)<EOL>v = self.linterp(timevar[i:i+<NUM_LIT:2>], v, currenttime)<EOL>w = self.linterp(timevar[i:i+<NUM_LIT:2>], w, currenttime)<EOL>if self.temp_name is not None and self.salt_name is not None:<EOL><INDENT>temp = self.linterp(timevar[i:i+<NUM_LIT:2>], temp, currenttime)<EOL>salt = self.linterp(timevar[i:i+<NUM_LIT:2>], salt, currenttime)<EOL><DEDENT>if self.temp_name is None:<EOL><INDENT>temp = np.nan<EOL><DEDENT>if self.salt_name is None:<EOL><INDENT>salt = np.nan<EOL><DEDENT><DEDENT>except StandardError:<EOL><INDENT>logger.error("<STR_LIT>")<EOL>raise<EOL><DEDENT>finally:<EOL><INDENT>if self.caching is True:<EOL><INDENT>self.dataset.closenc()<EOL>with self.read_lock:<EOL><INDENT>self.read_count.value -= <NUM_LIT:1><EOL>self.has_read_lock.remove(os.getpid())<EOL><DEDENT><DEDENT><DEDENT>return u, v, w, temp, salt<EOL>
Method to streamline request for data from cache, Uses linear interpolation bewtween timesteps to get u,v,w,temp,salt
f3630:c2:m4
def data_nearest(self, i, currenttime):
if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT>if self.need_data(i):<EOL><INDENT>self.data_request_lock.acquire()<EOL>self.has_data_request_lock.value = os.getpid()<EOL>try:<EOL><INDENT>if self.need_data(i):<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT>self.dataset.opennc()<EOL>indices = self.dataset.get_indices('<STR_LIT:u>', timeinds=[np.asarray([i-<NUM_LIT:1>])], point=self.part.location )<EOL>self.dataset.closenc()<EOL>with self.read_lock:<EOL><INDENT>self.read_count.value -= <NUM_LIT:1><EOL>self.has_read_lock.remove(os.getpid())<EOL><DEDENT>self.point_get.value = [indices[<NUM_LIT:0>]+<NUM_LIT:1>, indices[-<NUM_LIT:2>], indices[-<NUM_LIT:1>]]<EOL>self.get_data.value = True<EOL>if self.active.value is True:<EOL><INDENT>while self.get_data.value is True:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>timer.sleep(<NUM_LIT:2>)<EOL>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except StandardError:<EOL><INDENT>raise<EOL><DEDENT>finally:<EOL><INDENT>self.has_data_request_lock.value = -<NUM_LIT:1><EOL>self.data_request_lock.release()<EOL><DEDENT><DEDENT>if self.caching is True:<EOL><INDENT>with self.read_lock:<EOL><INDENT>self.read_count.value += <NUM_LIT:1><EOL>self.has_read_lock.append(os.getpid())<EOL><DEDENT><DEDENT>try:<EOL><INDENT>self.dataset.opennc()<EOL>u = np.mean(np.mean(self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i])], point=self.part.location )))<EOL>v = np.mean(np.mean(self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i])], point=self.part.location )))<EOL>if '<STR_LIT:w>' in self.dataset.nc.variables:<EOL><INDENT>w = np.mean(np.mean(self.dataset.get_values('<STR_LIT:w>', timeindsf=[np.asarray([i])], point=self.part.location )))<EOL><DEDENT>else:<EOL><INDENT>w = <NUM_LIT:0.0><EOL><DEDENT>if self.temp_name is not None and self.salt_name is not None:<EOL><INDENT>temp = np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location )))<EOL>salt = np.mean(np.mean(self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location )))<EOL><DEDENT>if np.isnan(u).any() or np.isnan(v).any() or np.isnan(w).any():<EOL><INDENT>uarray1 = self.dataset.get_values('<STR_LIT:u>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>varray1 = self.dataset.get_values('<STR_LIT:v>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>if '<STR_LIT:w>' in self.dataset.nc.variables:<EOL><INDENT>warray1 = self.dataset.get_values('<STR_LIT:w>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>w = warray1.mean()<EOL><DEDENT>else:<EOL><INDENT>w = <NUM_LIT:0.0><EOL><DEDENT>if self.temp_name is not None and self.salt_name is not None:<EOL><INDENT>temparray1 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>saltarray1 = self.dataset.get_values('<STR_LIT>', timeinds=[np.asarray([i])], point=self.part.location, num=<NUM_LIT:2>)<EOL>temp = temparray1.mean()<EOL>salt = saltarray1.mean()<EOL><DEDENT>u = uarray1.mean()<EOL>v = varray1.mean()<EOL><DEDENT>if self.temp_name is None:<EOL><INDENT>temp = np.nan<EOL><DEDENT>if self.salt_name is None:<EOL><INDENT>salt = np.nan<EOL><DEDENT><DEDENT>except StandardError:<EOL><INDENT>logger.error("<STR_LIT>")<EOL>raise<EOL><DEDENT>finally:<EOL><INDENT>if self.caching is True:<EOL><INDENT>self.dataset.closenc()<EOL>with self.read_lock:<EOL><INDENT>self.read_count.value -= <NUM_LIT:1><EOL>self.has_read_lock.remove(os.getpid())<EOL><DEDENT><DEDENT><DEDENT>return u, v, w, temp, salt<EOL>
Method to streamline request for data from cache, Uses nearest time to get u,v,w,temp,salt
f3630:c2:m5
def boundary_interaction(self, **kwargs):
particle = kwargs.pop('<STR_LIT>')<EOL>starting = kwargs.pop('<STR_LIT>')<EOL>ending = kwargs.pop('<STR_LIT>')<EOL>if self.useshore:<EOL><INDENT>intersection_point = self._shoreline.intersect(start_point=starting.point, end_point=ending.point)<EOL>if intersection_point:<EOL><INDENT>hitpoint = Location4D(point=intersection_point['<STR_LIT>'], time=starting.time + (ending.time - starting.time))<EOL>particle.location = hitpoint<EOL>resulting_point = self._shoreline.react(start_point=starting,<EOL>end_point=ending,<EOL>hit_point=hitpoint,<EOL>reverse_distance=self.reverse_distance,<EOL>feature=intersection_point['<STR_LIT>'],<EOL>distance=kwargs.get('<STR_LIT>'),<EOL>angle=kwargs.get('<STR_LIT>'),<EOL>azimuth=kwargs.get('<STR_LIT>'),<EOL>reverse_azimuth=kwargs.get('<STR_LIT>'))<EOL>ending.latitude = resulting_point.latitude<EOL>ending.longitude = resulting_point.longitude<EOL>ending.depth = resulting_point.depth<EOL>logger.debug("<STR_LIT>" % (particle.logstring(), hitpoint.logstring(), ending.logstring()))<EOL><DEDENT><DEDENT>if self.usebathy:<EOL><INDENT>if not particle.settled:<EOL><INDENT>bintersect = self._bathymetry.intersect(start_point=starting, end_point=ending)<EOL>if bintersect:<EOL><INDENT>pt = self._bathymetry.react(type='<STR_LIT>', start_point=starting, end_point=ending)<EOL>logger.debug("<STR_LIT>" % (particle.logstring(), ending.logstring(), pt.logstring()))<EOL>ending.latitude = pt.latitude<EOL>ending.longitude = pt.longitude<EOL>ending.depth = pt.depth<EOL><DEDENT><DEDENT><DEDENT>if self.usesurface:<EOL><INDENT>if ending.depth > <NUM_LIT:0>:<EOL><INDENT>logger.debug("<STR_LIT>" % particle.logstring())<EOL>ending.depth = <NUM_LIT:0><EOL><DEDENT><DEDENT>particle.location = ending<EOL>return<EOL>
Returns a list of Location4D objects
f3630:c2:m7
def __init__(self, **kwargs):
<EOL>self._dataset = None<EOL>self._use_shoreline = kwargs.pop('<STR_LIT>', True)<EOL>self._use_bathymetry = kwargs.pop('<STR_LIT>', True)<EOL>self._use_seasurface = kwargs.pop('<STR_LIT>', True)<EOL>self._depth = kwargs.pop('<STR_LIT>', <NUM_LIT:0>)<EOL>self._npart = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>self.start = kwargs.pop('<STR_LIT:start>')<EOL>if self.start == None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if self.start.tzinfo is None:<EOL><INDENT>self.start = self.start.replace(tzinfo=pytz.utc)<EOL><DEDENT>self.start = self.start.astimezone(pytz.utc)<EOL>self._step = kwargs.pop('<STR_LIT>', <NUM_LIT>)<EOL>self._models = kwargs.pop('<STR_LIT>', None)<EOL>self._dirty = True<EOL>self.particles = []<EOL>self._time_chunk = kwargs.get('<STR_LIT>', <NUM_LIT:10>)<EOL>self._horiz_chunk = kwargs.get('<STR_LIT>', <NUM_LIT:5>)<EOL>self.time_method = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.shoreline_path = kwargs.get("<STR_LIT>", None)<EOL>self.shoreline_feature = kwargs.get("<STR_LIT>", None)<EOL>self.reverse_distance = kwargs.get("<STR_LIT>", <NUM_LIT:100>)<EOL>self.datetimes = []<EOL>if "<STR_LIT>" in kwargs:<EOL><INDENT>self.geometry = kwargs.pop('<STR_LIT>')<EOL>if not isinstance(self.geometry, Point) and not isinstance(self.geometry, Polygon) and not isinstance(self.geometry, MultiPolygon):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif "<STR_LIT>" and "<STR_LIT>" in kwargs:<EOL><INDENT>self.geometry = Point(kwargs.pop('<STR_LIT>'), kwargs.pop('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>self._nstep = kwargs.pop('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>
Mandatory named arguments: * geometry (Shapely Geometry Object) no default * depth (meters) default 0 * start (DateTime Object) none * step (seconds) default 3600 * npart (number of particles) default 1 * nstep (number of steps) no default * models (list object) no default, so far there is a transport model and a behavior model geometry is interchangeable (if it is a point release) with: * latitude (DD) no default * longitude (DD) no default * depth (meters) default 0
f3631:c0:m0
def export(self, folder_path, format=None):
if format is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>format = format.lower()<EOL>if format == "<STR_LIT>" or format[-<NUM_LIT:4>:] == "<STR_LIT>":<EOL><INDENT>ex.Trackline.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes)<EOL><DEDENT>elif format == "<STR_LIT>" or format == "<STR_LIT>" or format[-<NUM_LIT:3>:] == "<STR_LIT>":<EOL><INDENT>ex.GDALShapefile.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes)<EOL><DEDENT>elif format == "<STR_LIT>" or format[-<NUM_LIT:2>:] == "<STR_LIT>":<EOL><INDENT>ex.NetCDF.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes, summary=str(self))<EOL><DEDENT>elif format == "<STR_LIT>" or format[-<NUM_LIT:3>:] == "<STR_LIT>" or format[-<NUM_LIT:6>:] == "<STR_LIT>":<EOL><INDENT>ex.Pickle.export(folder=folder_path, particles=self.particles, datetimes=self.datetimes)<EOL><DEDENT>
General purpose export method, gets file type from filepath extension Valid output formats currently are: Trackline: trackline or trkl or *.trkl Shapefile: shapefile or shape or shp or *.shp NetCDF: netcdf or nc or *.nc
f3631:c0:m11
def new(arg_name, annotated_with=None):
if annotated_with is not None:<EOL><INDENT>annotation = annotations.Annotation(annotated_with)<EOL><DEDENT>else:<EOL><INDENT>annotation = annotations.NO_ANNOTATION<EOL><DEDENT>return BindingKey(arg_name, annotation)<EOL>
Creates a BindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated binding key Returns: a new BindingKey
f3634:m0
def __init__(self, name, annotation):
self._name = name<EOL>self._annotation = annotation<EOL>
Initializer. Args: name: the name of the bound arg annotation: an Annotation
f3634:c0:m0
def copy_args_to_internal_fields(fn):
return _copy_args_to_fields(fn, '<STR_LIT>', '<STR_LIT:_>')<EOL>
Copies the initializer args to internal member fields. This is a decorator that applies to __init__.
f3639:m0
def copy_args_to_public_fields(fn):
return _copy_args_to_fields(fn, '<STR_LIT>', '<STR_LIT>')<EOL>
Copies the initializer args to public member fields. This is a decorator that applies to __init__.
f3639:m1
def get_unbound_arg_names(arg_names, arg_binding_keys):
bound_arg_names = [abk._arg_name for abk in arg_binding_keys]<EOL>return [arg_name for arg_name in arg_names<EOL>if arg_name not in bound_arg_names]<EOL>
Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of arg names that is a (possibly empty, possibly non-proper) subset of arg_names
f3641:m0
def create_kwargs(arg_binding_keys, provider_fn):
return {arg_binding_key._arg_name: provider_fn(arg_binding_key)<EOL>for arg_binding_key in arg_binding_keys}<EOL>
Creates a kwargs map for the given arg binding keys. Args: arg_binding_keys: a sequence of ArgBindingKey for some function's args provider_fn: a function that takes an ArgBindingKey and returns whatever is bound to that binding key Returns: a (possibly empty) map from arg name to provided value
f3641:m1
def new(arg_name, annotated_with=None):
if arg_name.startswith(_PROVIDE_PREFIX):<EOL><INDENT>binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:]<EOL>provider_indirection = provider_indirections.INDIRECTION<EOL><DEDENT>else:<EOL><INDENT>binding_key_name = arg_name<EOL>provider_indirection = provider_indirections.NO_INDIRECTION<EOL><DEDENT>binding_key = binding_keys.new(binding_key_name, annotated_with)<EOL>return ArgBindingKey(arg_name, binding_key, provider_indirection)<EOL>
Creates an ArgBindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated arg binding key Returns: a new ArgBindingKey
f3641:m2
def can_apply_to_one_of_arg_names(self, arg_names):
return self._arg_name in arg_names<EOL>
Returns whether this object can apply to one of the arg names.
f3641:c0:m6
def conflicts_with_any_arg_binding_key(self, arg_binding_keys):
return self._arg_name in [abk._arg_name for abk in arg_binding_keys]<EOL>
Returns whether this arg binding key conflicts with others. One arg binding key conflicts with another if they are for the same arg name, regardless of whether they have the same annotation (or lack thereof). Args: arg_binding_keys: a sequence of ArgBindingKey Returns: True iff some element of arg_binding_keys is for the same arg name as this binding key
f3641:c0:m7
def _get_type_name(target_thing):
thing = target_thing<EOL>if hasattr(thing, '<STR_LIT>'):<EOL><INDENT>return thing.im_class.__name__<EOL><DEDENT>if inspect.ismethod(thing):<EOL><INDENT>for cls in inspect.getmro(thing.__self__.__class__):<EOL><INDENT>if cls.__dict__.get(thing.__name__) is thing:<EOL><INDENT>return cls.__name__<EOL><DEDENT><DEDENT>thing = thing.__func__<EOL><DEDENT>if inspect.isfunction(thing) and hasattr(thing, '<STR_LIT>'):<EOL><INDENT>qualifier = thing.__qualname__<EOL>if LOCALS_TOKEN in qualifier:<EOL><INDENT>return _get_local_type_name(thing)<EOL><DEDENT>return _get_external_type_name(thing)<EOL><DEDENT>return inspect.getmodule(target_thing).__name__<EOL>
Functions, bound methods and unbound methods change significantly in Python 3. For instance: class SomeObject(object): def method(): pass In Python 2: - Unbound method inspect.ismethod(SomeObject.method) returns True - Unbound inspect.isfunction(SomeObject.method) returns False - Unbound hasattr(SomeObject.method, 'im_class') returns True - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns True In Python 3: - Unbound method inspect.ismethod(SomeObject.method) returns False - Unbound inspect.isfunction(SomeObject.method) returns True - Unbound hasattr(SomeObject.method, 'im_class') returns False - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns False This method tries to consolidate the approach for retrieving the enclosing type of a bound/unbound method and functions.
f3643:m3
def new_object_graph(<EOL>modules=finding.ALL_IMPORTED_MODULES, classes=None, binding_specs=None,<EOL>only_use_explicit_bindings=False, allow_injecting_none=False,<EOL>configure_method_name='<STR_LIT>',<EOL>dependencies_method_name='<STR_LIT>',<EOL>get_arg_names_from_class_name=(<EOL>bindings.default_get_arg_names_from_class_name),<EOL>get_arg_names_from_provider_fn_name=(<EOL>providing.default_get_arg_names_from_provider_fn_name),<EOL>id_to_scope=None, is_scope_usable_from_scope=lambda _1, _2: True,<EOL>use_short_stack_traces=True):
try:<EOL><INDENT>if modules is not None and modules is not finding.ALL_IMPORTED_MODULES:<EOL><INDENT>support.verify_module_types(modules, '<STR_LIT>')<EOL><DEDENT>if classes is not None:<EOL><INDENT>support.verify_class_types(classes, '<STR_LIT>')<EOL><DEDENT>if binding_specs is not None:<EOL><INDENT>support.verify_subclasses(<EOL>binding_specs, bindings.BindingSpec, '<STR_LIT>')<EOL><DEDENT>if get_arg_names_from_class_name is not None:<EOL><INDENT>support.verify_callable(get_arg_names_from_class_name,<EOL>'<STR_LIT>')<EOL><DEDENT>if get_arg_names_from_provider_fn_name is not None:<EOL><INDENT>support.verify_callable(get_arg_names_from_provider_fn_name,<EOL>'<STR_LIT>')<EOL><DEDENT>if is_scope_usable_from_scope is not None:<EOL><INDENT>support.verify_callable(is_scope_usable_from_scope,<EOL>'<STR_LIT>')<EOL><DEDENT>injection_context_factory = injection_contexts.InjectionContextFactory(<EOL>is_scope_usable_from_scope)<EOL>id_to_scope = scoping.get_id_to_scope_with_defaults(id_to_scope)<EOL>bindable_scopes = scoping.BindableScopes(id_to_scope)<EOL>known_scope_ids = id_to_scope.keys()<EOL>found_classes = finding.find_classes(modules, classes)<EOL>if only_use_explicit_bindings:<EOL><INDENT>implicit_class_bindings = []<EOL><DEDENT>else:<EOL><INDENT>implicit_class_bindings = bindings.get_implicit_class_bindings(<EOL>found_classes, get_arg_names_from_class_name)<EOL><DEDENT>explicit_bindings = bindings.get_explicit_class_bindings(<EOL>found_classes, get_arg_names_from_class_name)<EOL>binder = bindings.Binder(explicit_bindings, known_scope_ids)<EOL>required_bindings = required_bindings_lib.RequiredBindings()<EOL>if binding_specs is not None:<EOL><INDENT>binding_specs = list(binding_specs)<EOL>processed_binding_specs = set()<EOL>while binding_specs:<EOL><INDENT>binding_spec = binding_specs.pop()<EOL>if binding_spec in processed_binding_specs:<EOL><INDENT>continue<EOL><DEDENT>processed_binding_specs.add(binding_spec)<EOL>all_kwargs = {'<STR_LIT>': binder.bind,<EOL>'<STR_LIT>': required_bindings.require}<EOL>has_configure = hasattr(binding_spec, configure_method_name)<EOL>if has_configure:<EOL><INDENT>configure_method = getattr(binding_spec, configure_method_name)<EOL>configure_kwargs = _pare_to_present_args(<EOL>all_kwargs, configure_method)<EOL>if not configure_kwargs:<EOL><INDENT>raise errors.ConfigureMethodMissingArgsError(<EOL>configure_method, all_kwargs.keys())<EOL><DEDENT>try:<EOL><INDENT>configure_method(**configure_kwargs)<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>has_configure = False<EOL><DEDENT><DEDENT>dependencies = None<EOL>if hasattr(binding_spec, dependencies_method_name):<EOL><INDENT>dependencies_method = (<EOL>getattr(binding_spec, dependencies_method_name))<EOL>dependencies = dependencies_method()<EOL>binding_specs.extend(dependencies)<EOL><DEDENT>provider_bindings = bindings.get_provider_bindings(<EOL>binding_spec, known_scope_ids,<EOL>get_arg_names_from_provider_fn_name)<EOL>explicit_bindings.extend(provider_bindings)<EOL>if (not has_configure and<EOL>not dependencies and<EOL>not provider_bindings):<EOL><INDENT>raise errors.EmptyBindingSpecError(binding_spec)<EOL><DEDENT><DEDENT><DEDENT>binding_key_to_binding, collided_binding_key_to_bindings = (<EOL>bindings.get_overall_binding_key_to_binding_maps(<EOL>[implicit_class_bindings, explicit_bindings]))<EOL>binding_mapping = bindings.BindingMapping(<EOL>binding_key_to_binding, collided_binding_key_to_bindings)<EOL>binding_mapping.verify_requirements(required_bindings.get())<EOL><DEDENT>except errors.Error as e:<EOL><INDENT>if use_short_stack_traces:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>is_injectable_fn = {True: decorators.is_explicitly_injectable,<EOL>False: (lambda cls: True)}[only_use_explicit_bindings]<EOL>obj_provider = object_providers.ObjectProvider(<EOL>binding_mapping, bindable_scopes, allow_injecting_none)<EOL>return ObjectGraph(<EOL>obj_provider, injection_context_factory, is_injectable_fn,<EOL>use_short_stack_traces)<EOL>
Creates a new object graph. Args: modules: the modules in which to search for classes for which to create implicit bindings; if None, then no modules; by default, all modules imported at the time of calling this method classes: the classes for which to create implicit bindings; if None (the default), then no classes binding_specs: the BindingSpec subclasses to get bindings and provider methods from; if None (the default), then no binding specs only_use_explicit_bindings: whether to use only explicit bindings (i.e., created by binding specs or @pinject.injectable, etc.) allow_injecting_none: whether to allow a provider method to provide None configure_method_name: the name of binding specs' configure method dependencies_method_name: the name of binding specs' dependencies method get_arg_names_from_class_name: a function mapping a class name to a sequence of the arg names to which those classes should be implicitly bound (if any) get_arg_names_from_provider_fn_name: a function mapping a provider method name to a sequence of the arg names for which that method is a provider (if any) id_to_scope: a map from scope ID to the concrete Scope implementation instance for that scope is_scope_usable_from_scope: a function taking two scope IDs and returning whether an object in the first scope can be injected into an object from the second scope; by default, injection is allowed from any scope into any other scope use_short_stack_traces: whether to shorten the stack traces for exceptions that Pinject raises, so that they don't contain the innards of Pinject Returns: an ObjectGraph Raises: Error: the object graph is not creatable as specified
f3646:m0
def provide(self, cls):
support.verify_class_type(cls, '<STR_LIT>')<EOL>if not self._is_injectable_fn(cls):<EOL><INDENT>provide_loc = locations.get_back_frame_loc()<EOL>raise errors.NonExplicitlyBoundClassError(provide_loc, cls)<EOL><DEDENT>try:<EOL><INDENT>return self._obj_provider.provide_class(<EOL>cls, self._injection_context_factory.new(cls.__init__),<EOL>direct_init_pargs=[], direct_init_kwargs={})<EOL><DEDENT>except errors.Error as e:<EOL><INDENT>if self._use_short_stack_traces:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>
Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable
f3646:c0:m1
def __init__(self, is_scope_usable_from_scope_fn):
self._is_scope_usable_from_scope_fn = is_scope_usable_from_scope_fn<EOL>
Initializer. Args: is_scope_usable_from_scope_fn: a function taking two scope IDs and returning whether an object in the first scope can be injected into an object from the second scope
f3648:c0:m0
def new(self, injection_site_fn):
return _InjectionContext(<EOL>injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED,<EOL>is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn)<EOL>
Creates a _InjectionContext. Args: injection_site_fn: the initial function being injected into Returns: a new empty _InjectionContext in the default scope
f3648:c0:m1
def __init__(self, injection_site_fn, binding_stack, scope_id,<EOL>is_scope_usable_from_scope_fn):
self._injection_site_fn = injection_site_fn<EOL>self._binding_stack = binding_stack<EOL>self._scope_id = scope_id<EOL>self._is_scope_usable_from_scope_fn = is_scope_usable_from_scope_fn<EOL>
Initializer. Args: injection_site_fn: the function currently being injected into binding_stack: a sequence of the bindings whose use in injection is in-progress, from the highest level (first) to the current level (last) scope_id: the scope ID of the current (last) binding's scope is_scope_usable_from_scope_fn: a function taking two scope IDs and returning whether an object in the first scope can be injected into an object from the second scope
f3648:c1:m0
def get_child(self, injection_site_fn, binding):
child_scope_id = binding.scope_id<EOL>new_binding_stack = self._binding_stack + [binding]<EOL>if binding in self._binding_stack:<EOL><INDENT>raise errors.CyclicInjectionError(new_binding_stack)<EOL><DEDENT>if not self._is_scope_usable_from_scope_fn(<EOL>child_scope_id, self._scope_id):<EOL><INDENT>raise errors.BadDependencyScopeError(<EOL>self.get_injection_site_desc(),<EOL>self._scope_id, child_scope_id, binding.binding_key)<EOL><DEDENT>return _InjectionContext(<EOL>injection_site_fn, new_binding_stack, child_scope_id,<EOL>self._is_scope_usable_from_scope_fn)<EOL>
Creates a child injection context. A "child" injection context is a context for a binding used to inject something into the current binding's provided value. Args: injection_site_fn: the child function being injected into binding: a Binding Returns: a new _InjectionContext
f3648:c1:m1
def get_injection_site_desc(self):
return locations.get_name_and_loc(self._injection_site_fn)<EOL>
Returns a description of the current injection site.
f3648:c1:m2
def __init__(self, annotation_obj):
self._annotation_obj = annotation_obj<EOL>
Initializer. Args: annotation_obj: the annotation object, which can be any object that implements __eq__() and __hash__()
f3650:c0:m0
def as_adjective(self):
return '<STR_LIT>'.format(self._annotation_obj)<EOL>
Returns the annotation as an adjective phrase. For example, if the annotation object is '3', then the annotation adjective phrase is 'annotated with "3"'. Returns: an annotation adjective phrase
f3650:c0:m1
def annotate_arg(arg_name, with_annotation):
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)<EOL>return _get_pinject_wrapper(locations.get_back_frame_loc(),<EOL>arg_binding_key=arg_binding_key)<EOL>
Adds an annotation to an injected arg. arg_name must be one of the named args of the decorated function, i.e., @annotate_arg('foo', with_annotation='something') def a_function(foo): # ... is OK, but @annotate_arg('foo', with_annotation='something') def a_function(bar, **kwargs): # ... is not. The same arg (on the same function) may not be annotated twice. Args: arg_name: the name of the arg to annotate on the decorated function with_annotation: an annotation object Returns: a function that will decorate functions passed to it
f3651:m0
def inject(arg_names=None, all_except=None):
back_frame_loc = locations.get_back_frame_loc()<EOL>if arg_names is not None and all_except is not None:<EOL><INDENT>raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc)<EOL><DEDENT>for arg, arg_value in [('<STR_LIT>', arg_names), ('<STR_LIT>', all_except)]:<EOL><INDENT>if arg_value is not None:<EOL><INDENT>if not arg_value:<EOL><INDENT>raise errors.EmptySequenceArgError(back_frame_loc, arg)<EOL><DEDENT>if (not support.is_sequence(arg_value) or<EOL>support.is_string(arg_value)):<EOL><INDENT>raise errors.WrongArgTypeError(<EOL>arg, '<STR_LIT>', type(arg_value).__name__)<EOL><DEDENT><DEDENT><DEDENT>if arg_names is None and all_except is None:<EOL><INDENT>all_except = []<EOL><DEDENT>return _get_pinject_wrapper(<EOL>back_frame_loc, inject_arg_names=arg_names,<EOL>inject_all_except_arg_names=all_except)<EOL>
Marks an initializer explicitly as injectable. An initializer marked with @inject will be usable even when setting only_use_explicit_bindings=True when calling new_object_graph(). This decorator can be used on an initializer or provider method to separate the injectable args from the args that will be passed directly. If arg_names is specified, then it must be a sequence, and only those args are injected (and the rest must be passed directly). If all_except is specified, then it must be a sequence, and only those args are passed directly (and the rest must be specified). If neither arg_names nor all_except are specified, then all args are injected (and none may be passed directly). arg_names or all_except, when specified, must not be empty and must contain a (possibly empty, possibly non-proper) subset of the named args of the decorated function. all_except may not be all args of the decorated function (because then why call that provider method or initialzer via Pinject?). At most one of arg_names and all_except may be specified. A function may be decorated by @inject at most once.
f3651:m1
def injectable(fn):
return inject()(fn)<EOL>
Deprecated. Use @inject() instead. TODO(kurts): remove after 2014/6/30.
f3651:m2
def provides(arg_name=None, annotated_with=None, in_scope=None):
if arg_name is None and annotated_with is None and in_scope is None:<EOL><INDENT>raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc())<EOL><DEDENT>return _get_pinject_wrapper(locations.get_back_frame_loc(),<EOL>provider_arg_name=arg_name,<EOL>provider_annotated_with=annotated_with,<EOL>provider_in_scope_id=in_scope)<EOL>
Modifies the binding of a provider method. If arg_name is specified, then the created binding is for that arg name instead of the one gotten from the provider method name (e.g., 'foo' from 'provide_foo'). If annotated_with is specified, then the created binding includes that annotation object. If in_scope is specified, then the created binding is in the scope with that scope ID. At least one of the args must be specified. A provider method may not be decorated with @provides() twice. Args: arg_name: the name of the arg to annotate on the decorated function annotated_with: an annotation object in_scope: a scope ID Returns: a function that will decorate functions passed to it
f3651:m3
def get_provider_fn_decorations(provider_fn, default_arg_names):
if hasattr(provider_fn, _IS_WRAPPER_ATTR):<EOL><INDENT>provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR)<EOL>if provider_decorations:<EOL><INDENT>expanded_provider_decorations = []<EOL>for provider_decoration in provider_decorations:<EOL><INDENT>if provider_decoration.in_scope_id is None:<EOL><INDENT>provider_decoration.in_scope_id = scoping.DEFAULT_SCOPE<EOL><DEDENT>if provider_decoration.arg_name is not None:<EOL><INDENT>expanded_provider_decorations.append(provider_decoration)<EOL><DEDENT>else:<EOL><INDENT>expanded_provider_decorations.extend(<EOL>[ProviderDecoration(default_arg_name,<EOL>provider_decoration.annotated_with,<EOL>provider_decoration.in_scope_id)<EOL>for default_arg_name in default_arg_names])<EOL><DEDENT><DEDENT>return expanded_provider_decorations<EOL><DEDENT><DEDENT>return [ProviderDecoration(default_arg_name,<EOL>annotated_with=None,<EOL>in_scope_id=scoping.DEFAULT_SCOPE)<EOL>for default_arg_name in default_arg_names]<EOL>
Retrieves the provider method-relevant info set by decorators. If any info wasn't set by decorators, then defaults are returned. Args: provider_fn: a (possibly decorated) provider function default_arg_names: the (possibly empty) arg names to use if none were specified via @provides() Returns: a sequence of ProviderDecoration
f3651:m4
def get_overall_binding_key_to_binding_maps(bindings_lists):
binding_key_to_binding = {}<EOL>collided_binding_key_to_bindings = {}<EOL>for index, bindings in enumerate(bindings_lists):<EOL><INDENT>is_final_index = (index == (len(bindings_lists) - <NUM_LIT:1>))<EOL>handle_binding_collision_fn = {<EOL>True: _handle_explicit_binding_collision,<EOL>False: _handle_implicit_binding_collision}[is_final_index]<EOL>this_binding_key_to_binding, this_collided_binding_key_to_bindings = (<EOL>_get_binding_key_to_binding_maps(<EOL>bindings, handle_binding_collision_fn))<EOL>for good_binding_key in this_binding_key_to_binding:<EOL><INDENT>collided_binding_key_to_bindings.pop(good_binding_key, None)<EOL><DEDENT>binding_key_to_binding.update(this_binding_key_to_binding)<EOL>collided_binding_key_to_bindings.update(<EOL>this_collided_binding_key_to_bindings)<EOL><DEDENT>return binding_key_to_binding, collided_binding_key_to_bindings<EOL>
bindings_lists from lowest to highest priority. Last item in bindings_lists is assumed explicit.
f3653:m3
def default_get_arg_names_from_class_name(class_name):
parts = []<EOL>rest = class_name<EOL>if rest.startswith('<STR_LIT:_>'):<EOL><INDENT>rest = rest[<NUM_LIT:1>:]<EOL><DEDENT>while True:<EOL><INDENT>m = re.match(r'<STR_LIT>', rest)<EOL>if m is None:<EOL><INDENT>break<EOL><DEDENT>parts.append(m.group(<NUM_LIT:1>))<EOL>rest = m.group(<NUM_LIT:2>)<EOL><DEDENT>if not parts:<EOL><INDENT>return []<EOL><DEDENT>return ['<STR_LIT:_>'.join(part.lower() for part in parts)]<EOL>
Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding arg names, e.g., ["foo_bar"]
f3653:m4
def new_in_default_scope(binding_key):
return bindings_lib.new_binding_to_instance(<EOL>binding_key, '<STR_LIT>', scoping.DEFAULT_SCOPE,<EOL>get_binding_loc_fn=lambda: '<STR_LIT>')<EOL>
Returns a new Binding in the default scope. Args: binding_key: a BindingKey proviser_fn: a function taking a InjectionContext and ObjectGraph and returning an instance of the bound value Returns: a Binding
f3658:m0
def MOSQ_MSB(A):
return (( A & <NUM_LIT>) >> <NUM_LIT:8>)<EOL>
get most significant byte.
f3680:m0
def MOSQ_LSB(A):
return (A & <NUM_LIT>)<EOL>
get less significant byte.
f3680:m1
def connect(sock, addr):
try:<EOL><INDENT>sock.connect(addr)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return (ssl.SSLError, e.strerror if e.strerror else e.message)<EOL><DEDENT>except socket.herror as xxx_todo_changeme:<EOL><INDENT>(_, msg) = xxx_todo_changeme.args<EOL>return (socket.herror, msg)<EOL><DEDENT>except socket.gaierror as xxx_todo_changeme1:<EOL><INDENT>(_, msg) = xxx_todo_changeme1.args<EOL>return (socket.gaierror, msg)<EOL><DEDENT>except socket.timeout:<EOL><INDENT>return (socket.timeout, "<STR_LIT>")<EOL><DEDENT>except socket.error as e:<EOL><INDENT>return (socket.error, e.strerror if e.strerror else e.message)<EOL><DEDENT>return None<EOL>
Connect to some addr.
f3680:m2
def read(sock, count):
data = None<EOL>try:<EOL><INDENT>data = sock.recv(count)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return data, e.errno, e.strerror if strerror else e.message<EOL><DEDENT>except socket.herror as xxx_todo_changeme2:<EOL><INDENT>(errnum, errmsg) = xxx_todo_changeme2.args<EOL>return data, errnum, errmsg<EOL><DEDENT>except socket.gaierror as xxx_todo_changeme3:<EOL><INDENT>(errnum, errmsg) = xxx_todo_changeme3.args<EOL>return data, errnum, errmsg<EOL><DEDENT>except socket.timeout:<EOL><INDENT>return data, errno.ETIMEDOUT, "<STR_LIT>"<EOL><DEDENT>except socket.error as xxx_todo_changeme4:<EOL><INDENT>(errnum, errmsg) = xxx_todo_changeme4.args<EOL>return data, errnum, errmsg<EOL><DEDENT>ba_data = bytearray(data)<EOL>if len(ba_data) == <NUM_LIT:0>:<EOL><INDENT>return ba_data, errno.ECONNRESET, "<STR_LIT>"<EOL><DEDENT>return ba_data, <NUM_LIT:0>, "<STR_LIT>"<EOL>
Read from socket and return it's byte array representation. count = number of bytes to read
f3680:m3
def write(sock, payload):
try:<EOL><INDENT>length = sock.send(payload)<EOL><DEDENT>except ssl.SSLError as e:<EOL><INDENT>return -<NUM_LIT:1>, (ssl.SSLError, e.strerror if strerror else e.message)<EOL><DEDENT>except socket.herror as xxx_todo_changeme5:<EOL><INDENT>(_, msg) = xxx_todo_changeme5.args<EOL>return -<NUM_LIT:1>, (socket.error, msg)<EOL><DEDENT>except socket.gaierror as xxx_todo_changeme6:<EOL><INDENT>(_, msg) = xxx_todo_changeme6.args<EOL>return -<NUM_LIT:1>, (socket.gaierror, msg)<EOL><DEDENT>except socket.timeout:<EOL><INDENT>return -<NUM_LIT:1>, (socket.timeout, "<STR_LIT>")<EOL><DEDENT>except socket.error as xxx_todo_changeme7:<EOL><INDENT>(_, msg) = xxx_todo_changeme7.args<EOL>return -<NUM_LIT:1>, (socket.error, msg)<EOL><DEDENT>return length, None<EOL>
Write payload to socket.
f3680:m4
def setkeepalives(sock):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, <NUM_LIT:1>)<EOL>
set sock to be keepalive socket.
f3680:m5
def loop(self, timeout = <NUM_LIT:1>):
rlist = [self.sock]<EOL>wlist = []<EOL>if len(self.out_packet) > <NUM_LIT:0>:<EOL><INDENT>wlist.append(self.sock)<EOL><DEDENT>to_read, to_write, _ = select.select(rlist, wlist, [], timeout)<EOL>if len(to_read) > <NUM_LIT:0>:<EOL><INDENT>ret, _ = self.loop_read()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT><DEDENT>if len(to_write) > <NUM_LIT:0>:<EOL><INDENT>ret, _ = self.loop_write()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT><DEDENT>self.loop_misc()<EOL>return NC.ERR_SUCCESS<EOL>
Main loop.
f3682:c0:m1
def loop_read(self):
ret, bytes_received = self.packet_read()<EOL>return ret, bytes_received<EOL>
Read loop.
f3682:c0:m2
def loop_write(self):
ret, bytes_written = self.packet_write()<EOL>return ret, bytes_written<EOL>
Write loop.
f3682:c0:m3
def loop_misc(self):
self.check_keepalive()<EOL>if self.last_retry_check + <NUM_LIT:1> < time.time():<EOL><INDENT>pass<EOL><DEDENT>return NC.ERR_SUCCESS<EOL>
Misc loop.
f3682:c0:m4
def check_keepalive(self):
if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive:<EOL><INDENT>if self.state == NC.CS_CONNECTED:<EOL><INDENT>self.send_pingreq()<EOL><DEDENT>else:<EOL><INDENT>self.socket_close()<EOL><DEDENT><DEDENT>
Send keepalive/PING if necessary.
f3682:c0:m5
def packet_handle(self):
cmd = self.in_packet.command & <NUM_LIT><EOL>if cmd == NC.CMD_CONNACK:<EOL><INDENT>return self.handle_connack()<EOL><DEDENT>elif cmd == NC.CMD_PINGRESP:<EOL><INDENT>return self.handle_pingresp()<EOL><DEDENT>elif cmd == NC.CMD_PUBLISH:<EOL><INDENT>return self.handle_publish()<EOL><DEDENT>elif cmd == NC.CMD_PUBACK:<EOL><INDENT>return self.handle_puback()<EOL><DEDENT>elif cmd == NC.CMD_PUBREC:<EOL><INDENT>return self.handle_pubrec()<EOL><DEDENT>elif cmd == NC.CMD_PUBREL:<EOL><INDENT>return self.handle_pubrel()<EOL><DEDENT>elif cmd == NC.CMD_PUBCOMP:<EOL><INDENT>return self.handle_pubcomp()<EOL><DEDENT>elif cmd == NC.CMD_SUBSCRIBE:<EOL><INDENT>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>elif cmd == NC.CMD_SUBACK:<EOL><INDENT>return self.handle_suback()<EOL><DEDENT>elif cmd == NC.CMD_UNSUBSCRIBE:<EOL><INDENT>print("<STR_LIT>")<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>elif cmd == NC.CMD_UNSUBACK:<EOL><INDENT>return self.handle_unsuback()<EOL><DEDENT>else:<EOL><INDENT>self.logger.warning("<STR_LIT>", cmd)<EOL>return NC.ERR_PROTOCOL<EOL><DEDENT>
Incoming packet handler dispatcher.
f3682:c0:m6
def connect(self, version = <NUM_LIT:3>, clean_session = <NUM_LIT:1>, will = None):
self.clean_session = clean_session<EOL>self.will = None<EOL>if will is not None:<EOL><INDENT>self.will = NyamukMsg(<EOL>topic = will['<STR_LIT>'],<EOL>payload = utf8encode(will.get('<STR_LIT:message>','<STR_LIT>')),<EOL>qos = will.get('<STR_LIT>', <NUM_LIT:0>),<EOL>retain = will.get('<STR_LIT>', False)<EOL>)<EOL><DEDENT>pkt = MqttPkt()<EOL>pkt.connect_build(self, self.keep_alive, clean_session, version = version)<EOL>self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<EOL>if self.ssl:<EOL><INDENT>opts = {<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': ssl.PROTOCOL_TLSv1<EOL>}<EOL>opts.update(self.ssl_opts)<EOL>try:<EOL><INDENT>self.sock = ssl.wrap_socket(self.sock, **opts)<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.logger.error("<STR_LIT>".format(e))<EOL>return NC.ERR_UNKNOWN<EOL><DEDENT><DEDENT>nyamuk_net.setkeepalives(self.sock)<EOL>self.logger.info("<STR_LIT>", self.server)<EOL>err = nyamuk_net.connect(self.sock,(self.server, self.port))<EOL>if err != None:<EOL><INDENT>self.logger.error(err[<NUM_LIT:1>])<EOL>return NC.ERR_UNKNOWN<EOL><DEDENT>self.sock.setblocking(<NUM_LIT:0>)<EOL>return self.packet_queue(pkt)<EOL>
Connect to server.
f3682:c0:m7
def disconnect(self):
self.logger.info("<STR_LIT>")<EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.state = NC.CS_DISCONNECTING<EOL>ret = self.send_disconnect()<EOL>ret2, bytes_written = self.packet_write()<EOL>self.socket_close()<EOL>return ret<EOL>
Disconnect from server.
f3682:c0:m8
def subscribe(self, topic, qos):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", topic)<EOL>return self.send_subscribe(False, [(utf8encode(topic), qos)])<EOL>
Subscribe to some topic.
f3682:c0:m9
def subscribe_multi(self, topics):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", '<STR_LIT:U+002CU+0020>'.join([t for (t,q) in topics]))<EOL>return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, qos) in topics])<EOL>
Subscribe to some topics.
f3682:c0:m10
def unsubscribe(self, topic):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", topic)<EOL>return self.send_unsubscribe(False, [utf8encode(topic)])<EOL>
Unsubscribe to some topic.
f3682:c0:m11
def unsubscribe_multi(self, topics):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", '<STR_LIT:U+002CU+0020>'.join(topics))<EOL>return self.send_unsubscribe(False, [utf8encode(topic) for topic in topics])<EOL>
Unsubscribe to some topics.
f3682:c0:m12
def send_disconnect(self):
return self.send_simple_command(NC.CMD_DISCONNECT)<EOL>
Send disconnect command.
f3682:c0:m13
def send_subscribe(self, dup, topics):
pkt = MqttPkt()<EOL>pktlen = <NUM_LIT:2> + sum([<NUM_LIT:2>+len(topic)+<NUM_LIT:1> for (topic, qos) in topics])<EOL>pkt.command = NC.CMD_SUBSCRIBE | (dup << <NUM_LIT:3>) | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = pktlen<EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>mid = self.mid_generate()<EOL>pkt.write_uint16(mid)<EOL>for (topic, qos) in topics:<EOL><INDENT>pkt.write_string(topic)<EOL>pkt.write_byte(qos)<EOL><DEDENT>return self.packet_queue(pkt)<EOL>
Send subscribe COMMAND to server.
f3682:c0:m14
def send_unsubscribe(self, dup, topics):
pkt = MqttPkt()<EOL>pktlen = <NUM_LIT:2> + sum([<NUM_LIT:2>+len(topic) for topic in topics])<EOL>pkt.command = NC.CMD_UNSUBSCRIBE | (dup << <NUM_LIT:3>) | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = pktlen<EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>mid = self.mid_generate()<EOL>pkt.write_uint16(mid)<EOL>for topic in topics:<EOL><INDENT>pkt.write_string(topic)<EOL><DEDENT>return self.packet_queue(pkt)<EOL>
Send unsubscribe COMMAND to server.
f3682:c0:m15
def publish(self, topic, payload = None, qos = <NUM_LIT:0>, retain = False):
<EOL>payloadlen = len(payload)<EOL>if topic is None or qos < <NUM_LIT:0> or qos > <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>")<EOL>return NC.ERR_INVAL<EOL><DEDENT>if payloadlen > (<NUM_LIT> * <NUM_LIT> * <NUM_LIT>):<EOL><INDENT>self.logger.error("<STR_LIT>", payloadlen)<EOL>return NC.ERR_PAYLOAD_SIZE<EOL><DEDENT>mid = self.mid_generate()<EOL>if qos in (<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>):<EOL><INDENT>return self.send_publish(mid, topic, payload, qos, retain, False)<EOL><DEDENT>else:<EOL><INDENT>self.logger.error("<STR_LIT>", qos)<EOL><DEDENT>return NC.ERR_NOT_SUPPORTED<EOL>
Publish some payload to server.
f3682:c0:m16
def handle_connack(self):
self.logger.info("<STR_LIT>")<EOL>ret, flags = self.in_packet.read_byte()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>self.logger.error("<STR_LIT>")<EOL>return ret<EOL><DEDENT>session_present = flags & <NUM_LIT><EOL>ret, retcode = self.in_packet.read_byte()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventConnack(retcode, session_present)<EOL>self.push_event(evt)<EOL>if retcode == NC.CONNECT_ACCEPTED:<EOL><INDENT>self.state = NC.CS_CONNECTED<EOL>return NC.ERR_SUCCESS<EOL><DEDENT>elif retcode >= <NUM_LIT:1> and retcode <= <NUM_LIT:5>:<EOL><INDENT>return NC.ERR_CONN_REFUSED<EOL><DEDENT>else:<EOL><INDENT>return NC.ERR_PROTOCOL<EOL><DEDENT>
Handle incoming CONNACK command.
f3682:c0:m17
def handle_pingresp(self):
self.logger.debug("<STR_LIT>")<EOL>self.push_event(event.EventPingResp())<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PINGRESP packet.
f3682:c0:m18
def handle_suback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>qos_count = self.in_packet.remaining_length - self.in_packet.pos<EOL>granted_qos = bytearray(qos_count)<EOL>if granted_qos is None:<EOL><INDENT>return NC.ERR_NO_MEM<EOL><DEDENT>i = <NUM_LIT:0><EOL>while self.in_packet.pos < self.in_packet.remaining_length:<EOL><INDENT>ret, byte = self.in_packet.read_byte()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>granted_qos = None<EOL>return ret<EOL><DEDENT>granted_qos[i] = byte<EOL>i += <NUM_LIT:1><EOL><DEDENT>evt = event.EventSuback(mid, list(granted_qos))<EOL>self.push_event(evt)<EOL>granted_qos = None<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming SUBACK packet.
f3682:c0:m19
def handle_unsuback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventUnsuback(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming UNSUBACK packet.
f3682:c0:m20
def send_pingreq(self):
self.logger.debug("<STR_LIT>")<EOL>return self.send_simple_command(NC.CMD_PINGREQ)<EOL>
Send PINGREQ command to server.
f3682:c0:m21
def handle_publish(self):
self.logger.debug("<STR_LIT>")<EOL>header = self.in_packet.command<EOL>message = NyamukMsgAll()<EOL>message.direction = NC.DIRECTION_IN<EOL>message.dup = (header & <NUM_LIT>) >> <NUM_LIT:3><EOL>message.msg.qos = (header & <NUM_LIT>) >> <NUM_LIT:1><EOL>message.msg.retain = (header & <NUM_LIT>)<EOL>ret, ba_data = self.in_packet.read_string()<EOL>message.msg.topic = ba_data.decode('<STR_LIT:utf8>')<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>if message.msg.qos > <NUM_LIT:0>:<EOL><INDENT>ret, word = self.in_packet.read_uint16()<EOL>message.msg.mid = word<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT><DEDENT>message.msg.payloadlen = self.in_packet.remaining_length - self.in_packet.pos<EOL>if message.msg.payloadlen > <NUM_LIT:0>:<EOL><INDENT>ret, message.msg.payload = self.in_packet.read_bytes(message.msg.payloadlen)<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT><DEDENT>self.logger.debug("<STR_LIT>", message.dup, message.msg.qos, message.msg.retain)<EOL>self.logger.debug("<STR_LIT>", message.msg.mid, message.msg.topic, message.msg.payloadlen)<EOL>message.timestamp = time.time()<EOL>qos = message.msg.qos<EOL>if qos in (<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>):<EOL><INDENT>evt = event.EventPublish(message.msg)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL><DEDENT>else:<EOL><INDENT>return NC.ERR_PROTOCOL<EOL><DEDENT>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBLISH packet.
f3682:c0:m22
def send_publish(self, mid, topic, payload, qos, retain, dup):
self.logger.debug("<STR_LIT>")<EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>return self._do_send_publish(mid, utf8encode(topic), utf8encode(payload), qos, retain, dup)<EOL>
Send PUBLISH.
f3682:c0:m23
def handle_puback(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPuback(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBACK packet.
f3682:c0:m25
def handle_pubrec(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubrec(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBREC packet.
f3682:c0:m26
def handle_pubrel(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubrel(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBREL packet.
f3682:c0:m27
def handle_pubcomp(self):
self.logger.info("<STR_LIT>")<EOL>ret, mid = self.in_packet.read_uint16()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>evt = event.EventPubcomp(mid)<EOL>self.push_event(evt)<EOL>return NC.ERR_SUCCESS<EOL>
Handle incoming PUBCOMP packet.
f3682:c0:m28
def puback(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBACK<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>return self.packet_queue(pkt)<EOL>
Send PUBACK response to server.
f3682:c0:m29
def pubrel(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBREL | (<NUM_LIT:1> << <NUM_LIT:1>)<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>return self.packet_queue(pkt)<EOL>
Send PUBREL response to server.
f3682:c0:m30
def pubrec(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBREC<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>return self.packet_queue(pkt)<EOL>
Send PUBREC response to server.
f3682:c0:m31
def pubcomp(self, mid):
if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>self.logger.info("<STR_LIT>", mid)<EOL>pkt = MqttPkt()<EOL>pkt.command = NC.CMD_PUBCOMP<EOL>pkt.remaining_length = <NUM_LIT:2><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>pkt.write_uint16(mid)<EOL>return self.packet_queue(pkt)<EOL>
Send PUBCOMP response to server.
f3682:c0:m32
def dump(self):
print("<STR_LIT>")<EOL>print("<STR_LIT>", self.command)<EOL>print("<STR_LIT>", self.have_remaining)<EOL>print("<STR_LIT>", self.remaining_count)<EOL>print("<STR_LIT>", self.mid)<EOL>print("<STR_LIT>", self.remaining_mult)<EOL>print("<STR_LIT>", self.remaining_length)<EOL>print("<STR_LIT>", self.packet_length)<EOL>print("<STR_LIT>", self.to_process)<EOL>print("<STR_LIT>", self.pos)<EOL>print("<STR_LIT>", self.payload)<EOL>print("<STR_LIT>")<EOL>
Print packet content.
f3685:c0:m1
def alloc(self):
byte = <NUM_LIT:0><EOL>remaining_bytes = bytearray(<NUM_LIT:5>)<EOL>i = <NUM_LIT:0><EOL>remaining_length = self.remaining_length<EOL>self.payload = None<EOL>self.remaining_count = <NUM_LIT:0><EOL>loop_flag = True<EOL>while loop_flag:<EOL><INDENT>byte = remaining_length % <NUM_LIT><EOL>remaining_length = remaining_length / <NUM_LIT><EOL>if remaining_length > <NUM_LIT:0>:<EOL><INDENT>byte = byte | <NUM_LIT><EOL><DEDENT>remaining_bytes[self.remaining_count] = byte<EOL>self.remaining_count += <NUM_LIT:1><EOL>if not (remaining_length > <NUM_LIT:0> and self.remaining_count < <NUM_LIT:5>):<EOL><INDENT>loop_flag = False<EOL><DEDENT><DEDENT>if self.remaining_count == <NUM_LIT:5>:<EOL><INDENT>return NC.ERR_PAYLOAD_SIZE<EOL><DEDENT>self.packet_length = self.remaining_length + <NUM_LIT:1> + self.remaining_count<EOL>self.payload = bytearray(self.packet_length)<EOL>self.payload[<NUM_LIT:0>] = self.command<EOL>i = <NUM_LIT:0><EOL>while i < self.remaining_count:<EOL><INDENT>self.payload[i+<NUM_LIT:1>] = remaining_bytes[i]<EOL>i += <NUM_LIT:1><EOL><DEDENT>self.pos = <NUM_LIT:1> + self.remaining_count<EOL>return NC.ERR_SUCCESS<EOL>
from _mosquitto_packet_alloc.
f3685:c0:m2
def connect_build(self, nyamuk, keepalive, clean_session, retain = <NUM_LIT:0>, dup = <NUM_LIT:0>, version = <NUM_LIT:3>):
will = <NUM_LIT:0>; will_topic = None<EOL>byte = <NUM_LIT:0><EOL>client_id = utf8encode(nyamuk.client_id)<EOL>username = utf8encode(nyamuk.username) if nyamuk.username is not None else None<EOL>password = utf8encode(nyamuk.password) if nyamuk.password is not None else None<EOL>payload_len = <NUM_LIT:2> + len(client_id)<EOL>if nyamuk.will is not None:<EOL><INDENT>will = <NUM_LIT:1><EOL>will_topic = utf8encode(nyamuk.will.topic)<EOL>payload_len = payload_len + <NUM_LIT:2> + len(will_topic) + <NUM_LIT:2> + nyamuk.will.payloadlen<EOL><DEDENT>if username is not None:<EOL><INDENT>payload_len = payload_len + <NUM_LIT:2> + len(username)<EOL>if password != None:<EOL><INDENT>payload_len = payload_len + <NUM_LIT:2> + len(password)<EOL><DEDENT><DEDENT>self.command = NC.CMD_CONNECT<EOL>self.remaining_length = <NUM_LIT:12> + payload_len<EOL>rc = self.alloc()<EOL>if rc != NC.ERR_SUCCESS:<EOL><INDENT>return rc<EOL><DEDENT>self.write_string(getattr(NC, '<STR_LIT>'.format(version)))<EOL>self.write_byte( getattr(NC, '<STR_LIT>'.format(version)))<EOL>byte = (clean_session & <NUM_LIT>) << <NUM_LIT:1><EOL>if will:<EOL><INDENT>byte = byte | ((nyamuk.will.retain & <NUM_LIT>) << <NUM_LIT:5>) | ((nyamuk.will.qos & <NUM_LIT>) << <NUM_LIT:3>) | ((will & <NUM_LIT>) << <NUM_LIT:2>)<EOL><DEDENT>if nyamuk.username is not None:<EOL><INDENT>byte = byte | <NUM_LIT> << <NUM_LIT:7><EOL>if nyamuk.password is not None:<EOL><INDENT>byte = byte | <NUM_LIT> << <NUM_LIT:6><EOL><DEDENT><DEDENT>self.write_byte(byte)<EOL>self.write_uint16(keepalive)<EOL>self.write_string(client_id)<EOL>if will:<EOL><INDENT>self.write_string(will_topic)<EOL>self.write_string(nyamuk.will.payload)<EOL><DEDENT>if username is not None:<EOL><INDENT>self.write_string(username)<EOL>if password is not None:<EOL><INDENT>self.write_string(password)<EOL><DEDENT><DEDENT>nyamuk.keep_alive = keepalive<EOL>return NC.ERR_SUCCESS<EOL>
Build packet for CONNECT command.
f3685:c0:m4
def write_string(self, string):
self.write_uint16(len(string))<EOL>self.write_bytes(string, len(string))<EOL>
Write a string to this packet.
f3685:c0:m5
def write_uint16(self, word):
self.write_byte(nyamuk_net.MOSQ_MSB(word))<EOL>self.write_byte(nyamuk_net.MOSQ_LSB(word))<EOL>
Write 2 bytes.
f3685:c0:m6
def write_byte(self, byte):
self.payload[self.pos] = byte<EOL>self.pos = self.pos + <NUM_LIT:1><EOL>
Write one byte.
f3685:c0:m7
def write_bytes(self, data, n):
for pos in range(<NUM_LIT:0>, n):<EOL><INDENT>self.payload[self.pos + pos] = data[pos]<EOL><DEDENT>self.pos += n<EOL>
Write n number of bytes to this packet.
f3685:c0:m8
def read_byte(self):
if self.pos + <NUM_LIT:1> > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>byte = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>return NC.ERR_SUCCESS, byte<EOL>
Read a byte.
f3685:c0:m9
def read_uint16(self):
if self.pos + <NUM_LIT:2> > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL<EOL><DEDENT>msb = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>lsb = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL>word = (msb << <NUM_LIT:8>) + lsb<EOL>return NC.ERR_SUCCESS, word<EOL>
Read 2 bytes.
f3685:c0:m10
def read_bytes(self, count):
if self.pos + count > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>ba = bytearray(count)<EOL>for x in range(<NUM_LIT:0>, count):<EOL><INDENT>ba[x] = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL><DEDENT>return NC.ERR_SUCCESS, ba<EOL>
Read count number of bytes.
f3685:c0:m11
def read_string(self):
rc, length = self.read_uint16()<EOL>if rc != NC.ERR_SUCCESS:<EOL><INDENT>return rc, None<EOL><DEDENT>if self.pos + length > self.remaining_length:<EOL><INDENT>return NC.ERR_PROTOCOL, None<EOL><DEDENT>ba = bytearray(length)<EOL>if ba is None:<EOL><INDENT>return NC.ERR_NO_MEM, None<EOL><DEDENT>for x in range(<NUM_LIT:0>, length):<EOL><INDENT>ba[x] = self.payload[self.pos]<EOL>self.pos += <NUM_LIT:1><EOL><DEDENT>return NC.ERR_SUCCESS, ba<EOL>
Read string.
f3685:c0:m12
def __init__(self, client_id, username, password,<EOL>server, port, keepalive, ssl, ssl_opts):
self.client_id = client_id<EOL>self.username = username<EOL>self.password = password<EOL>self.server = server<EOL>self.port = port<EOL>self.ssl = ssl<EOL>self.ssl_opts = ssl_opts<EOL>self.address = "<STR_LIT>"<EOL>self.keep_alive = keepalive<EOL>self.clean_session = <NUM_LIT:1><EOL>self.state = NC.CS_NEW<EOL>self.last_msg_in = time.time()<EOL>self.last_msg_out = time.time()<EOL>self.last_mid = <NUM_LIT:0><EOL>self.out_packet = []<EOL>self.in_packet = MqttPkt()<EOL>self.in_packet.packet_cleanup()<EOL>self.sock = NC.INVALID_SOCKET<EOL>self.will = None<EOL>self.message_retry = NC.MESSAGE_RETRY<EOL>self.last_retry_check = <NUM_LIT:0><EOL>self.messages = None<EOL>self.bridge = None<EOL>self.log_priorities = -<NUM_LIT:1><EOL>self.log_destinations = -<NUM_LIT:1><EOL>self.host = None<EOL>self.as_broker = False<EOL>self.event_list = []<EOL>
Constructor
f3688:c0:m0
def pop_event(self):
if len(self.event_list) > <NUM_LIT:0>:<EOL><INDENT>evt = self.event_list.pop(<NUM_LIT:0>)<EOL>return evt<EOL><DEDENT>return None<EOL>
Pop an event from event_list.
f3688:c0:m1
def push_event(self, evt):
self.event_list.append(evt)<EOL>
Add an event to event_list.
f3688:c0:m2
def mid_generate(self):
self.last_mid += <NUM_LIT:1><EOL>if self.last_mid == <NUM_LIT:0>:<EOL><INDENT>self.last_mid += <NUM_LIT:1><EOL><DEDENT>return self.last_mid<EOL>
Generate mid. TODO : check.
f3688:c0:m3