def on_message(self, msg): cmd = msg[3] if cmd == 0x02: # напряжение оборотыm v = int.from_bytes(msg[6:8], "little") * LoraProtocol.VOLTAGE_MULTIPLIER rpm = int.from_bytes(msg[4:6], "little") * 60 * LoraProtocol.RPM_CALIBRATION lora_publisher.publish(aiopubsub.Key('obj', 'voltage'), v) lora_publisher.publish(aiopubsub.Key('obj', 'rpm'), rpm) lora_publisher.publish(aiopubsub.Key('message', 'nmea2000'), create_rmp_message(rpm)) lora_publisher.publish(aiopubsub.Key('message', 'nmea2000'), create_voltage_message(v)) if cmd == 0x03: # геркон протечка напряжение на батарейке lora_publisher.publish( aiopubsub.Key('obj', 'flood'), dict( water=msg[4], door=msg[5], battery=msg[6], ))
def save(self): choice = self.cleaned_data["choice"] choice.votes += 1 choice.save() publisher = aiopubsub.Publisher(hub, aiopubsub.Key("poll")) publisher.publish(aiopubsub.Key("on_vote"), self.poll)
async def test_publish(publisher, throttled_publisher, subscriber): k = aiopubsub.Key('a', 'b') subscriber.subscribe(aiopubsub.Key('Tester', *k)) await throttled_publisher.publish(k, 'message') assert publisher.has_subscribers(k) _, message = await subscriber.consume() assert message == 'message'
def __init__(self,hub,name,sdpfilename,w,h,dojpeg=True,dortp=True,netmode=True,jpeginfo="",h264info=""): # create two UdpServer self.size = (w,h) self.name = name self.process = None print ("ffmpeg subscriber",name) self.subscriber = aiopubsub.Subscriber(hub,"") self.subscriber.subscribe(name) self.subscriber.add_listener(name, self.push,last=True) self.netmode = netmode if dortp: self.rtppub = aiopubsub.Publisher(hub, prefix = aiopubsub.Key(name,'rtp')) self.hserver = RTPStreamServer(self.onrtp) self.hserver.bind(0,family=socket.AF_INET) self.hserver.start() hports = self.hserver.ports() #h264info.split(" ") + rtppart = ["-f","rtp","-sdp_file",sdpfilename] + ["rtp://127.0.0.0:%d" % hports[0]] else: hports = [] self.rtppub = None self.hserver = None rtppart = [] # TODO expose: new JPEG packet event if dojpeg: self.jpegpub = aiopubsub.Publisher(hub, prefix = aiopubsub.Key(name,'jpeg')) self.jserver = JpegStreamServer(self.onjpeg) self.jserver.listen(0) jports = self.jserver.ports() #jpeginfo.split(" ") + jpegpart = ["-f","mjpeg"] + ["tcp://127.0.0.0:%d" % jports[0]] # TODO expose: new RTP packet event else: jports = [] self.jpegpub = None self.jserver = None jpegpart = [] if not dojpeg and not dortp: self.args = None return else: beforesource = ["ffmpeg","-y","-f","rawvideo","-r","30","-pix_fmt","rgb32","-s","%dx%d" % (w,h)] print ("ffmpeg: ","jports",jports,"hports",hports) if not self.netmode: args = beforesource + ["-i","-"] + jpegpart + rtppart else: self.lserver = ForwardStreamServer() self.lserver.listen(0) lports = self.lserver.ports() args = beforesource + ["-i","tcp://127.0.0.0:%d" % lports[0]] + jpegpart + rtppart self.args = args self.tl = None
def test_hub_publish_match_wildcard(hub, callback, benchmark, subscribers_count, matching_keys): inv_matching_keys = int(1 / matching_keys) for i in range(subscribers_count): if i % inv_matching_keys == 0: k = aiopubsub.Key('a', '*') else: k = aiopubsub.Key('c', '*') hub.add_subscriber(k, callback) k = aiopubsub.Key('a', 'b') benchmark(hub.publish, k, 'message')
async def fake_lora_generator(): while True: lora_publisher.publish(aiopubsub.Key('message', 'nmea2000'), create_rmp_message(randint(2000, 2500))) # lora_publisher.publish(aiopubsub.Key('message', 'nmea2000'), # create_position_message(13.165 + randint(1, 100) / 10, 55.11 + randint(1, 100) / 10)) lora_publisher.publish(aiopubsub.Key('message', 'nmea2000'), create_voltage_message(13.12)) lora_publisher.publish( aiopubsub.Key('message', 'nmea2000'), create_position_message(43.51567302199084, 16.231514405287953)) await asyncio.sleep(1)
def __init__(self,hub,name): self.name = name print ("PILCompressor subscribing to",name) self.jpegpub = aiopubsub.Publisher(hub, prefix = aiopubsub.Key(name,'jpeg')) self.subscriber = aiopubsub.Subscriber(hub,"") self.subscriber.subscribe(name) self.subscriber.add_listener(name, self.push,last=True)
def push(self,key,ta_img): #print ("PIL received",img) now = time.time() ta = ta_img[0] buffer = io.BytesIO() ta_img[1].save(buffer, "JPEG") #print ("pil",now-ta,ta) self.jpegpub.publish(aiopubsub.Key(),(ta_img[0],buffer.getvalue()))
def init_pubsub(): """Initiate pubsub module, create default publisher""" try: this.hub = aiopubsub.Hub() this.publisher = aiopubsub.Publisher(this.hub, prefix=aiopubsub.Key()) except Exception: logger.exception('Error initiationg pubsub module') raise
def __init__(self): logwood.basic_config() self.hub = aiopubsub.Hub() self.publisher = aiopubsub.Publisher(self.hub, prefix=aiopubsub.Key('peer')) self.subscriber_epoch = aiopubsub.Subscriber(self.hub, 'epoch_subscr') self.subscriber_connection = aiopubsub.Subscriber( self.hub, 'conn_subscr') self.subscriber_pom = aiopubsub.Subscriber(self.hub, 'pom_subsrc') sub_key_epoch = aiopubsub.Key('peer', 'epoch') self.subscriber_epoch.subscribe(sub_key_epoch) sub_key_conn = aiopubsub.Key('peer', 'connection') self.subscriber_connection.subscribe(sub_key_conn) sub_key_pom = aiopubsub.Key('peer', 'pom') self.subscriber_pom.subscribe(sub_key_pom)
async def console_log(msg, modal_guid): """ Method used in AxAction terminal. It sends message to vue via ws """ ax_pubsub.publisher.publish( aiopubsub.Key('console_log'), { 'text': msg, 'modal_guid': modal_guid }) await asyncio.sleep(0.01)
async def terminal_log(msg): """ Method used in AxTerminal. It sends message to vue via ws """ if not this.current_modal_guid: return False ax_pubsub.publisher.publish(aiopubsub.Key('console_log'), { 'text': msg, 'modal_guid': current_modal_guid }) await asyncio.sleep(0.01)
async def resolve_on_poll_updated(root, info): subscriber = aiopubsub.Subscriber(hub, str(uuid.uuid4())) subscriber.subscribe(aiopubsub.Key("poll", "on_vote")) yield Poll.objects.first() while True: _, message = await subscriber.consume() yield message
def __init__(self,hub,parts=None,rate=30): self.sct = mss.mss() self.rate = rate self.consumers = [] if parts is None: self.isfull = True self.parts = [(0,0,self.sct.monitors[1][0],self.sct.monitors[1][1])] else: self.isfull = False self.parts=parts self.pubs=[] for i in range(0,len(self.parts)): self.pubs.append(aiopubsub.Publisher(hub,aiopubsub.Key()))
async def test_publish_delay(throttled_publisher, subscriber): k = aiopubsub.Key('a', 'b') subscriber.subscribe(aiopubsub.Key('Tester', *k)) await throttled_publisher.publish(k, 'message') await throttled_publisher.publish(k, 'message') async def consume(): await asyncio.sleep(0.01) await subscriber.consume() async def block_publish(): await throttled_publisher.publish(k, 'message') publish_task = asyncio.ensure_future(block_publish()) await asyncio.sleep(0.02) assert not publish_task.done() consume_task = asyncio.ensure_future(consume()) await consume_task await asyncio.sleep(0.02) done, _ = await asyncio.wait([publish_task], timeout=0.5) assert publish_task in done
async def resolve_action_notify(self, info, form_db_name, row_guid=None): """ Web-socket subscription on every performed action AxForm.vue will display message, that current row have been modified AxGrid.vue will reload data of grid Args: form_db_name (str): db_name of AxForm row_guid (str): If it is set, then the subscriber will be notified only on actions performed with surtain row. AxGrid is notified on every action AxForm is notified only on row actions Returns: payload (Dict): Dict containing action info: form_guid (str): AxForm.guid of current form form_icon (str): font-awesome icon form_db_name (str): AxForm.db_name of current form row_guid (str): Guid of row on wich action is performed modal_guid (str): Guid generated by AxForm.vue. It used in web-socket subscribtion. If current form is performing this action - it doesnot need to notify user of performed action action_guid (str): Current action guid action_db_name (str): Db name of current action action_icon (str): font-awesome icon of current action """ try: del info subscriber = aiopubsub.Subscriber( ax_pubsub.hub, 'action_notify_subscriber') subscriber.subscribe(aiopubsub.Key('do_action')) while True: key, payload = await subscriber.consume() del key if payload['form_db_name'] == form_db_name: if row_guid is None or row_guid == payload['row_guid']: message = ActionNotifyMessage( form_guid=payload['form_guid'], form_icon=payload['form_icon'], form_db_name=payload['form_db_name'], row_guid=payload['row_guid'], modal_guid=payload['modal_guid'], action_guid=payload['action_guid'], action_db_name=payload['action_db_name'], action_icon=payload['action_icon']) yield message except asyncio.CancelledError: await subscriber.remove_all_listeners()
def grabber(self): # check if consumer read tt = time.time() n = 1 while True: nxt = gen.sleep(1.0/self.rate) # Start the clock. ta = time.time() #print (n/(ta-tt)) n = n + 1 img = self.grab() if len(self.parts) > 1 or not self.isfull: pa = [img.crop((p[0],p[1],p[0]+p[2],p[1]+p[3])) for p in self.parts] else: pa = [img] for i,c,img in zip(range(0,len(pa)),self.pubs,pa): self.pubs[i].publish(aiopubsub.Key("area%d"%i),(ta,img)) yield nxt
async def resolve_console_notify(self, info, modal_guid): """ Web-socket subscription on ax terminal print """ try: del info subscriber = aiopubsub.Subscriber( ax_pubsub.hub, 'action_notify_subscriber') subscriber.subscribe(aiopubsub.Key('console_log')) this.action_loop = asyncio.get_event_loop() while True: key, payload = await subscriber.consume() await asyncio.sleep(0.1) del key if payload['modal_guid'] == modal_guid: message = ConsoleMessage( text=payload['text'], modal_guid=payload['modal_guid']) yield message except asyncio.CancelledError: await subscriber.remove_all_listeners() except Exception: # pylint: disable=broad-except logger.exception('Error in gql sub resolve_console_notify.')
import aiopubsub gHub = aiopubsub.Hub() publisher = aiopubsub.Publisher(gHub, prefix=aiopubsub.Key('g')) keyAll = aiopubsub.Key('*') keyPsJson = aiopubsub.Key('g', 'pubsub', 'json') keyChatAll = aiopubsub.Key('g', 'pubsub', 'chat', '*') keyChatChannels = aiopubsub.Key('g', 'pubsub', 'chat', 'channels') def makeKeyChatChannel(channel): return aiopubsub.Key('g', 'chat', 'channels', channel) def psSubscriber(sid): return aiopubsub.Subscriber(gHub, sid)
import aiopubsub hub = aiopubsub.Hub() canbus_publisher = aiopubsub.Publisher(hub, prefix=aiopubsub.Key("canbus")) lora_publisher = aiopubsub.Publisher(hub, prefix=aiopubsub.Key("lora"))
def onrtp(self,pkt): now = time.time() self.rtppub.publish(aiopubsub.Key(),(now,pkt))
def onjpeg(self,img): now = time.time() self.jpegpub.publish(aiopubsub.Key(),(now,img))
def makeKeyChatChannel(channel): return aiopubsub.Key('g', 'chat', 'channels', channel)