Exemplo n.º 1
0
    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],
                ))
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
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'
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
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')
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
 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)
Exemplo n.º 8
0
 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()))
Exemplo n.º 9
0
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
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
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)
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
 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()))
Exemplo n.º 15
0
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
Exemplo n.º 16
0
    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()
Exemplo n.º 17
0
 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 
Exemplo n.º 18
0
 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.')
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
import aiopubsub

hub = aiopubsub.Hub()

canbus_publisher = aiopubsub.Publisher(hub, prefix=aiopubsub.Key("canbus"))
lora_publisher = aiopubsub.Publisher(hub, prefix=aiopubsub.Key("lora"))
Exemplo n.º 21
0
 def onrtp(self,pkt):
     now = time.time()
     self.rtppub.publish(aiopubsub.Key(),(now,pkt))
Exemplo n.º 22
0
 def onjpeg(self,img):
     now = time.time()
     self.jpegpub.publish(aiopubsub.Key(),(now,img))
Exemplo n.º 23
0
def makeKeyChatChannel(channel):
    return aiopubsub.Key('g', 'chat', 'channels', channel)