8. Background channel task
8
# Send payload to locatin-check channels
async_to_sync(channel_layer.send)('location-check', {'type': 'position_check’,
'gps_serial': gps_serial, 'long': gps_long, 'lat': gps_lat})
class PositionCheckConsumer(SyncConsumer):
def position_check(self, message):
"""
Check if there are zones in wich GPS device is not
located and send those location on websocket
"""
# Filter associated Geofence zones in which device is not located
exclude_zones = GeofenceZone.objects.filter(gps=gps_device).exclude(geom__contains=last_location)
# If there are zones without GPS signal, send their ID via websocket
if exclude_zones.exists():
# Send payload to websocket
channel_layer = get_channel_layer()
group_name = 'device_{}'.format(message['gps_serial'])
data = {'type': 'zone warning', 'long': message['long'],
'lat': message['lat'], 'zone': [zone.id for zone in exclude_zones]}
async_to_sync(channel_layer.group_send)(
group_name,
{
'type': 'location_update',
'message': json.dumps(data)
}
)
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
url(r'^ws/gps/(?P<serial_number>[-w]+)/$', GpsLogConsumer)
])
),
'channel': ChannelNameRouter({
'location-check': PositionCheckConsumer,
})
})