Ejemplo n.º 1
0
    def __init__(self, logger, mqttConfig, devConfig, isNew=False):
        super().__init__(client_id=devConfig['location'] + '.' +
                         devConfig['name'])
        self.config = devConfig
        self.logger = logger

        if isNew:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Creating new device"
            )
            self.commandSet = CommandSet(
                emitter_gpio=self.config['commandSet']['emitterGpio'],
                receiver_gpio=self.config['commandSet']['receiverGpio'],
                description=self.config['commandSet']['description'])
        else:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Loading existing device"
            )
            self.commandSet = CommandSet.load(
                os.path.join('./commandSets',
                             self.config['commandSet']['manufacturer'],
                             self.config['commandSet']['model'] + '.json'))

        self.baseTopic = self.config['topicPrefix'] + '/' + self.config[
            'location'] + '/' + self.config['name'] + '/'
        self._initMqttClient(mqttConfig['user'], mqttConfig['broker'],
                             self.config['lastWill'])
Ejemplo n.º 2
0
 def __init__(self, device, gpio, commands):
     self.name = "device_" + str(device)
     self.TR_pin = gpio
     if not commands:
         self.controller = CommandSet(emitter_gpio=self.TR_pin,
                                      receiver_gpio=self.RR_pin,
                                      name=self.name)
     else:
         remote_json = json.dumps(self.build_json(commands))
         self.controller = CommandSet.from_json(remote_json)
Ejemplo n.º 3
0
 def __init__(self, filename=None, emitter=None, receiver=None):
     self.status = 0
     self.commands = ["start_stop", "home", "circle", "edge", "auto"]
     if filename is not None:
         self.controller = CommandSet.load(filename)
     elif emitter is not None and receiver is not None:
         self.controller = CommandSet(name="Eufy",
                                      emitter_gpio=emitter,
                                      receiver_gpio=receiver)
     else:
         raise
Ejemplo n.º 4
0
def send_command(command,
                 file=JSON_FILE,
                 device_type='*',
                 emitter_gpio=GPIO_EMITTER,
                 receiver_gpio=GPIO_RECEIVER):
    controller = CommandSet(name=device_type,
                            emitter_gpio=emitter_gpio,
                            receiver_gpio=receiver_gpio,
                            description=device_type)
    #Load from JSON:
    controller = CommandSet.load(file)
    controller.emit(command)
Ejemplo n.º 5
0
class IR:
    controller = None
    name = None
    TR_pin = None  # Transmitter GPIO pin
    RR_pin = 13  # Receiver GPIO pin

    def __init__(self, device, gpio, commands):
        self.name = "device_" + str(device)
        self.TR_pin = gpio
        if not commands:
            self.controller = CommandSet(emitter_gpio=self.TR_pin,
                                         receiver_gpio=self.RR_pin,
                                         name=self.name)
        else:
            remote_json = json.dumps(self.build_json(commands))
            self.controller = CommandSet.from_json(remote_json)

    def build_json(self, commands):
        data = '{'
        for command in commands:
            data = data + '"command_' + str(
                command['id']) + '": ' + command['signal'] + ','
        data = data[:-1] + '}'
        return {
            "type": "CommandSet",
            "name": self.name,
            "emitter_gpio": self.TR_pin,
            "receiver_gpio": self.RR_pin,
            "commands": json.loads(data),
            "description": ""
        }

    def record(self, command):
        self.controller.add("command_" + str(command))
        return self.controller.commands["command_" + str(command)].to_json()

    def send(self, command):
        self.controller.emit("command_" + str(command))

    def get_id(self):
        return self.name[7:]
Ejemplo n.º 6
0
class Eufy:
    def __init__(self, filename=None, emitter=None, receiver=None):
        self.status = 0
        self.commands = ["start_stop", "home", "circle", "edge", "auto"]
        if filename is not None:
            self.controller = CommandSet.load(filename)
        elif emitter is not None and receiver is not None:
            self.controller = CommandSet(name="Eufy",
                                         emitter_gpio=emitter,
                                         receiver_gpio=receiver)
        else:
            raise

    def pair(self):
        for c in self.commands:
            print("PAIR: ", c)
            self.controller.add(c)
            sleep(1)

        self.controller.save_as("eufy.json")

    def emit(self, v):
        if v == "start_stop":
            self.status = 2
        self.controller.emit(v)

    def print(self):
        return states[self.status]
Ejemplo n.º 7
0
# Create a CommandSet for your remote control
# GPIO for the IR receiver: 23
# GPIO for the IR transmitter: 22
from ircodec.command import CommandSet
controller = CommandSet(name='AC',emitter_gpio=14, receiver_gpio=15, description='AC')



# Add the keys
key=''

while key!='quit': 
    key=input('Enter the key name\n') 
    if key!='quit':
        controller.add(key)
     


# Save to JSON
file=input('Enter the device you want to store the keys (e.g. AC)\n')
controller.save_as('./ir_codes_modules/{}.json'.format(file))



Ejemplo n.º 8
0
# Create a CommandSet for your remote control
import time
from ircodec.command import CommandSet

controller = CommandSet(name='SAMSUNG-REMOTE',
                        emitter_gpio=14,
                        receiver_gpio=15)

# Add keys
print("NEXT KEY: power")
controller.add('power')
time.sleep(1)
print("NEXT KEY: source")
controller.add('source')
time.sleep(1)
print("NEXT KEY: volume_up")
controller.add('volume_up')
time.sleep(1)
print("NEXT KEY: volume_down")
controller.add('volume_down')
time.sleep(1)
print("NEXT KEY: mute")
controller.add('mute')
time.sleep(1)
print("NEXT KEY: program_up")
controller.add('program_up')
time.sleep(1)
print("NEXT KEY: program_down")
controller.add('program_down')
time.sleep(1)
print("NEXT KEY: guide")
Ejemplo n.º 9
0
#GPIO for the IR receiver: 23
#GPIO for the IR transmitter: 14
import time
import os

os.system ("sudo pigpiod")
from ircodec.command import CommandSet

controller = CommandSet.load('./Ardoor.json')
time.sleep (1)
controller.emit('Trigger')
print ('Sinyal terkirim')
Ejemplo n.º 10
0
# Create a CommandSet for your remote control
# GPIO for the IR receiver: 23
# GPIO for the IR transmitter: 22
from ircodec.command import CommandSet
# controller = CommandSet(emitter_gpio=16, receiver_gpio=20, description='AC Remote for RPi', name='AC Remote')

controller = CommandSet.load('ac.json')

while True:
    print("Enter input name")
    s = input()
    if s == "end":
        break

    # Add the volume up key
    # controller.add(s)
    # Connected to pigpio
    # Detecting IR command...
    # Received.

    # print("Ready IR receiver")
    # input()

    # Send the volume up command
    controller.emit(s)

    # Remove the volume up command
    # controller.remove('volume_up')

    # Examine the contents of the CommandSet
    # controller
Ejemplo n.º 11
0
    8376657,  # B
    8377425,  # C
    8377617,  # E (Ja ja, dit had D moeten zijn. Maar dan moest ik helemaal zo'n ding open schroeven en daar had ik geen zin in dus ik het het zo opgelost. Sue me.
    8377665  # D
]

rfGpioPort = 17

app = flask.Flask(__name__)
CORS(app)
# app.config["DEBUG"] = True

# to create a new controller:
# controller = CommandSet(emitter_gpio=22, receiver_gpio=23, description='TV remote', name='SamsungTV')

controller = CommandSet.load('samsung-tv.json')
commands = []
with open("commands.txt", "rb") as fp:
    commands = pickle.load(fp)


@app.route('/', methods=['GET'])
def home():
    return 'Online.\r\nGo to /send/ /update/ /add/ /remove/ or /get/'


@app.route('/send/<command>', methods=['PUT'])
def sendCommand(command):
    print('=> sending command: ' + command)
    controller.emit(command)
    return '{ "success":"true" }'
import time
from ircodec.command import CommandSet

controller = CommandSet(name='TEAC-REMOTE', emitter_gpio=14, receiver_gpio=15)

# Add keys
print("NEXT KEY: power")
controller.add('power')
time.sleep(1)
print("NEXT KEY: mute")
controller.add('mute')
time.sleep(1)
print("NEXT KEY: volume_down")
controller.add('volume_down')
time.sleep(1)
print("NEXT KEY: volume_up")
controller.add('volume_up')
time.sleep(1)
print("NEXT KEY: test_tone")
controller.add('test_tone')
time.sleep(1)
print("NEXT KEY: tape")
controller.add('tape')
time.sleep(1)
print("NEXT KEY: aux")
controller.add('aux')
time.sleep(1)
print("NEXT KEY: md-cdr")
controller.add('md-cdr')
time.sleep(1)
Ejemplo n.º 13
0
import time
from ircodec.command import CommandSet

controller = CommandSet(name='LED-REMOTE', emitter_gpio=14, receiver_gpio=15)

# Add keys
print("NEXT KEY: on")
controller.add('on')
time.sleep(1)
print("NEXT KEY: off")
controller.add('off')
time.sleep(1)
print("NEXT KEY: red")
controller.add('red')
time.sleep(1)
print("NEXT KEY: red_1")
controller.add('red_1')
time.sleep(1)
print("NEXT KEY: red_2")
controller.add('red_2')
time.sleep(1)
print("NEXT KEY: red_3")
controller.add('red_3')
time.sleep(1)
print("NEXT KEY: red_4")
controller.add('red_4')
time.sleep(1)
print("NEXT KEY: green")
controller.add('green')
time.sleep(1)
print("NEXT KEY: green_1")
Ejemplo n.º 14
0
def buka_pintu():
    from ircodec.command import CommandSet
    controller = CommandSet.load('Ardoor.json')
    time.sleep(1)
    controller.emit('Trigger')
    print('Sinyal terkirim')
Ejemplo n.º 15
0
class Device(mqtt.Client):
    # Constants
    STATUS_TOPIC = 'status'
    CMD_TOPIC = 'command'
    RESULT_TOPIC = 'result'

    ONLINE_MSG = 'ONLINE'
    OFFLINE_MSG = 'OFFLINE'
    SUCCESS_MSG = 'done'
    ERROR_MSG = 'unsupported'

    # Constructor
    def __init__(self, logger, mqttConfig, devConfig, isNew=False):
        super().__init__(client_id=devConfig['location'] + '.' +
                         devConfig['name'])
        self.config = devConfig
        self.logger = logger

        if isNew:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Creating new device"
            )
            self.commandSet = CommandSet(
                emitter_gpio=self.config['commandSet']['emitterGpio'],
                receiver_gpio=self.config['commandSet']['receiverGpio'],
                description=self.config['commandSet']['description'])
        else:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Loading existing device"
            )
            self.commandSet = CommandSet.load(
                os.path.join('./commandSets',
                             self.config['commandSet']['manufacturer'],
                             self.config['commandSet']['model'] + '.json'))

        self.baseTopic = self.config['topicPrefix'] + '/' + self.config[
            'location'] + '/' + self.config['name'] + '/'
        self._initMqttClient(mqttConfig['user'], mqttConfig['broker'],
                             self.config['lastWill'])

    # Init device mqtt client
    def _initMqttClient(self, user, broker, lastWill):
        willTopic = self.baseTopic + self.STATUS_TOPIC

        # Set client settings
        self.will_set(willTopic, self.OFFLINE_MSG, lastWill['qos'],
                      lastWill['retain'])
        self.username_pw_set(user['name'], user['password'])
        self.tls_set()
        self.tls_insecure_set(True)

        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Connecting to {broker['ip']}:{broker['port']}"
        )
        self.logger.debug(
            f"{self.config['location']}.{self.config['name']}: Connecting as {user['name']} with password {user['password']}"
        )

        # Connect to broker
        self.connect(broker['ip'], port=broker['port'])

        # Start network loop
        self.loop_start()

    # Publish command result
    def _publishCmdResult(self, success):
        resultTopic = self.baseTopic + self.RESULT_TOPIC
        if success:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Command sent"
            )
            self.publish(resultTopic, payload=self.SUCCESS_MSG)
        else:
            self.logger.info(
                f"{self.config['location']}.{self.config['name']}: Command unsupported"
            )
            self.publish(resultTopic, payload=self.ERROR_MSG)

    # On connection
    def on_connect(self, client, usrData, flags, rc):
        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Connected")
        self.logger.debug(
            f"{self.config['location']}.{self.config['name']}: rc {rc}")

        # Publish ONLINE status
        statusTopic = self.baseTopic + self.STATUS_TOPIC
        self.publish(statusTopic, payload=self.ONLINE_MSG, qos=1, retain=True)

        # Subscribing to command topic
        cmdTopic = self.baseTopic + self.CMD_TOPIC
        self.subscribe(cmdTopic)

    # On disconnect
    def on_disconnect(self, client, usrData, rc):
        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Disconnected")
        self.logger.debug(
            f"{self.config['location']}.{self.config['name']}: rc {rc}")

    # On message
    def on_message(self, client, usrData, msg):
        receivedMsg = msg.payload.decode('utf-8')
        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Message recieved {receivedMsg}"
        )
        for i in range(0, 4):
            self.logger.debug(
                f"{self.config['location']}.{self.config['name']}: Sending packet #{i}"
            )
            # TODO: Manage unsupported command
            self.commandSet.emit(
                receivedMsg, emit_gap=self.config['commandSet']['packetGap'])
        self._publishCmdResult(True)

    # On publish
    def on_publish(self, client, usrData, mid):
        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Message published"
        )
        self.logger.debug(
            f"{self.config['location']}.{self.config['name']}: mid {mid}")

    # On subscribe
    def on_subscribe(self, client, usrData, mid, grantedQoS):
        self.logger.info(
            f"{self.config['location']}.{self.config['name']}: Subscibed with QoS {grantedQoS}"
        )
        self.logger.debug(
            f"{self.config['location']}.{self.config['name']}: mid {mid}")

    # On log
    def on_log(self, client, usrData, logLevel, logMsg):
        switcher = {
            mqtt.MQTT_LOG_INFO: self.logger.info,
            mqtt.MQTT_LOG_NOTICE: self.logger.info,
            mqtt.MQTT_LOG_WARNING: self.logger.warning,
            mqtt.MQTT_LOG_ERR: self.logger.error,
            mqtt.MQTT_LOG_DEBUG: self.logger.debug,
        }
        switcher[logLevel](
            f"{self.config['location']}.{self.config['name']}: {logMsg}")

    # Set device config
    def setConfig(self, config):
        self.logger(
            f"{self.config['location']}.{self.config['name']}: Setting device config to {config}"
        )
        self.config = config

    # Get device config
    def getConfig(self):
        self.logger(
            f"{self.config['location']}.{self.config['name']}: Getting device config"
        )
        return self.config

    # Get command list
    def getCommandList(self):
        self.logger(
            f"{self.config['location']}.{self.config['name']}: Getting command list"
        )
        return self.commandSet.to_json()

    # Add a command
    def addCommand(self, command, description):
        self.logger(
            f"{self.config['location']}.{self.config['name']}: Adding command {command} to command set"
        )
        self.commandSet.add(command, description=description)

    # Delete a command
    def deleteCommand(self, command):
        self.logger(
            f"{self.config['location']}.{self.config['name']}: Deleting command {command} from command set"
        )
        self.commandSet.remove(command)

    # Save device Config
    def saveConfig(self):
        result = {'result': 'fail'}
        try:
            with open('./config/devices.json') as configFile:
                deviceConfigs = json.loads(configFile.read())
                devConfigItr = filter(
                    lambda device: device['name'] == self.config['name'],
                    deviceConfigs)
                deviceConfig = next(devConfigItr, None)
                if deviceConfig is not None:
                    deviceConfig = self.config
                else:
                    deviceConfigs.append(self.config)
                devConfigsContent = json.dumps(deviceConfigs,
                                               sort_keys=True,
                                               indent=2)
                configFile.write(devConfigsContent)
            result['result'] = 'success'
        except EnvironmentError:
            result['message'] = 'Error accessing devices configuration file!!'
        return result

    # Save device command set
    def saveCommandSet(self):
        result = {'result': 'fail'}
        try:
            self.commandSet.save_as(
                os.path.join('./commandSets',
                             self.config['commandSet'] + '.json'))
            result['result'] = 'success'
        except EnvironmentError:
            result['message'] = 'Error accessing command set file'
        return result