Skip to content

Instantly share code, notes, and snippets.

@griches
Last active January 22, 2016 02:54
Show Gist options
  • Save griches/07c921f6998e9148792b to your computer and use it in GitHub Desktop.
Save griches/07c921f6998e9148792b to your computer and use it in GitHub Desktop.
//
// ViewController.m
// LIFX
//
// Created by Gary Riches on 18/01/2016.
// Copyright © 2016 Gary Riches. All rights reserved.
//
#import "ViewController.h"
#import "GCDAsyncUdpSocket.h"
typedef struct {
/* frame */
uint16_t size;
uint16_t protocol:12;
uint8_t addressable:1;
uint8_t tagged:1;
uint8_t origin:2;
uint32_t source;
/* frame address */
uint8_t target[8];
uint8_t reserved[6];
uint8_t res_required:1;
uint8_t ack_required:1;
uint8_t :6;
uint8_t sequence;
/* protocol header */
uint64_t :64;
uint16_t type;
uint16_t reserved_header:16;
/* variable length payload follows */
} packet;
packet CreatePacket(){
packet Packet;
return Packet;
}
@interface ViewController () <GCDAsyncUdpSocketDelegate>
@property (nonatomic, strong) GCDAsyncUdpSocket *udpSocket;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
self.udpSocket.delegate = self;
// Discover
[self discover];
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", response);
}
- (void)discover {
[self.udpSocket enableBroadcast:YES error:nil];
self.udpSocket.delegate = self;
[self.udpSocket bindToPort:56700 error:nil];
[self.udpSocket beginReceiving:nil];
[self findBulbs];
[self performSelector:@selector(cancelFindBulbs) withObject:nil afterDelay:12];
}
- (void)findBulbs
{
packet discovery = CreatePacket();
discovery.protocol = 1024;
discovery.addressable = 1;
discovery.tagged = 1;
discovery.origin = 0;
discovery.source = 0;
bzero(discovery.target, sizeof(discovery.target));
bzero(discovery.reserved, sizeof(discovery.reserved));
discovery.res_required = 0;
discovery.ack_required = 0;
discovery.sequence = 0;
discovery.reserved_header = 0;
discovery.type = 2;
discovery.size = sizeof(discovery);
NSData *bytes = [NSData dataWithBytes:&discovery length:sizeof(discovery)];
[self.udpSocket sendData:bytes toHost:@"255.255.255.255" port:56700 withTimeout:-1 tag:1];
[self performSelector:@selector(findBulbs) withObject:nil afterDelay:1];
}
- (void)cancelFindBulbs
{
[self.udpSocket pauseReceiving];
[self.udpSocket enableBroadcast:NO error:nil];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment