Skip to content

Instantly share code, notes, and snippets.

@dequn
Created June 30, 2018 06:36
Show Gist options
  • Select an option

  • Save dequn/c1569c38bfd95a70c4bafc24b9189360 to your computer and use it in GitHub Desktop.

Select an option

Save dequn/c1569c38bfd95a70c4bafc24b9189360 to your computer and use it in GitHub Desktop.

Revisions

  1. dequn created this gist Jun 30, 2018.
    33 changes: 33 additions & 0 deletions channels.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@

    def handle(self, *args, **options):
    redis = get_redis_connection()
    ps = redis.pubsub()
    ps.subscribe([RELAY_CONTROL_RESULT_CHANNEL])
    for item in ps.listen():
    if item['type'] == 'message':
    data = item['data']
    equipment_id, return_state = data.decode('ascii').split(':')
    # equipment_id is group name
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
    equipment_id,
    {"type": "relay_message",
    # relay_message is a function, must be defined in a consumer which in the group name of `equipment_id`
    "return_state": int(return_state)
    }
    )
    class ExampleConsumer(AsyncWebsocketConsumer):
    async def connect(self):
    # ...code to parse equipment_id
    self.channel_layer.group_add(
    equipment_id,
    self.channel_name
    )
    # other code
    async def relay_message(self, event):
    return_state = event['return_state']
    # other code
    await self.send(text_data="some message send to client")
    # other function rewrite