Code Switcher
Code Switching Example #
This is an example of a code switcher between multiple different snippets of code. Pretend they’re all the same logic even though they’re just here for demonstration of the tab switcher and coming from different domains.
There is also has a feature of allowing specific page links to activate/override the tabs a little bit too. Try it out with these buttons below and then look at the URL in your browser.
Hand writing the CSS styles for the different tabs is a bit of a pain, but thankfully this is wrapped in a custom Hugo Shortcode I made so that I don’t have to think about it too much.
class _ReceiveStateMessages:
"""Context manager to receive state messages from the network."""
def __init__(self, timeout: float = 1.0) -> None:
"""Handle socket configuration."""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.settimeout(timeout)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def __enter__(self):
"""Send message on initialization."""
self.socket.bind(("", 8888))
return self
def __exit__(self, *args):
"""Close open socket."""
self.socket.close()
def __iter__(self):
"""Iteration over network messages."""
pattern = re.compile(b"\xfc[\x90-\xFF]\xff`\x01\n")
try:
_LOGGER.debug("Listening...")
while True:
message, address = self.socket.recvfrom(1024)
ip, port = address
_LOGGER.debug(
"Received message=%s from ip=%s port=[%s]", message, ip, port
)
if port == 8888 and pattern.match(message):
_LOGGER.debug("Processing state from ip=%s port=[%s]", ip, port)
parsed_message = self.parse_message(message[6:], ip)
if parsed_message:
_LOGGER.debug("Successfully parsed state message")
yield parsed_message
except socket.timeout:
return
@staticmethod
def parse_string(string: bytes) -> str:
"""Take bytes from packet into strimmed string."""
try:
return string.strip(b"\x00").decode("utf8").strip()
except (ValueError, TypeError):
_LOGGER.error(str(sys.exc_info()[1]))
return ""
@staticmethod
def parse_message(
message: bytes, ip: str
) -> Union[None, Dict[str, Union[str, int, bytes, datetime.datetime]]]:
"""Take a packet payload and convert to dictionary."""
if message[-2] == 1:
device_type = "DreamScreenHD"
elif message[-2] == 2:
device_type = "DreamScreen4K"
elif message[-2] == 3:
device_type = "SideKick"
elif message[-2] == 7:
device_type = "DreamScreenSolo"
else:
_LOGGER.debug("Unknown device type: %s", message[-2])
return None
parsed_message = {
"ip": ip,
"device_type": device_type,
"update_time": datetime.datetime.now(),
"recent_state_message": message,
} # type: Dict[str, Union[str, int, bytes, datetime.datetime]]
parsed_message.update(
{
"name": _ReceiveStateMessages.parse_string(message[0:16]),
"group_name": _ReceiveStateMessages.parse_string(message[16:32]),
"group_number": message[32],
"mode": message[33],
"brightness": message[34],
"ambient_color": message[40:43],
"ambient_scene": message[62],
}
)
_LOGGER.debug("Update: %s", parsed_message)
if device_type != "SideKick":
parsed_message.update(
{
"hdmi_input": message[73],
"hdmi_input_1_name": _ReceiveStateMessages.parse_string(
message[75:91]
),
"hdmi_input_2_name": _ReceiveStateMessages.parse_string(
message[91:107]
),
"hdmi_input_3_name": _ReceiveStateMessages.parse_string(
message[107:123]
),
"hdmi_active_channels": message[129],
"hdr_tone_remapping": message[139],
}
)
return parsed_message
func main() {
app := &cli.Command{
Name: "automidically",
Usage: "hooks MIDI device inputs to System Volume(s)",
Authors: []any{
mail.Address{Name: "Gregory Dosh"},
},
Version: fmt.Sprintf("%s-%s", buildVersion, buildCommit),
Action: automidicallyMain,
Flags: []cli.Flag{
&cli.StringFlag{
Sources: cli.EnvVars("CONFIG_FILENAME"),
Name: "config",
Aliases: []string{"c", "f", "config_filename", "filename"},
Usage: "specify the yml configuration location",
Destination: &configFilename,
Value: "config.yml",
},
&cli.StringFlag{
Sources: cli.EnvVars("LOG_LEVEL"),
Name: "log_level",
Aliases: []string{"l"},
Usage: "trace, debug, info, warn, error, fatal, panic",
Value: "info",
},
&cli.StringFlag{
Sources: cli.EnvVars("LOG_PATH"),
Name: "log_path",
Usage: "Set a path for the log file. Set empty to disable.",
Value: defaultLogFilename,
},
&cli.StringFlag{
Sources: cli.EnvVars("PROFILE_CPU"),
Name: "profile_cpu",
Aliases: []string{"pc"},
Hidden: true,
Destination: &profileCPUFilename,
},
&cli.StringFlag{
Sources: cli.EnvVars("PROFILE_MEMORY"),
Name: "profile_memory",
Aliases: []string{"pm"},
Hidden: true,
Destination: &profileMemoryFilename,
},
},
}
if err := app.Run(context.Background(), os.Args); err != nil {
log.Fatal(err)
}
}
pydreamscreen |Build Status|
============================
.. |Build Status| image:: https://travis-ci.org/GregoryDosh/pydreamscreen.svg?branch=master
:target: https://travis-ci.org/GregoryDosh/pydreamscreen
Python library for DreamScreen device discovery and manipulation for Wifi enabled DreamScreen Solo, HD, 4K, and SideKick devices.
Issues
======
Please submit issues `here <https://github.com/GregoryDosh/pydreamscreen/issues>`_.
- name: Template extra configuration files into place
become: true
ansible.builtin.template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: "{{ item['owner'] if 'owner' in item.keys() else DCAASS_CONFIG_USER_NAME }}"
group: "{{ item['group'] if 'group' in item.keys() else DCAASS_CONFIG_GROUP_NAME }}"
mode: "{{ item['mode'] if 'mode' in item else DCAASS_CONFIG_FILE_MODE }}"
register: _dcaass_extra_files
with_items: "{{ DCAASS_EXTRA_CONFIG_FILES }}"
notify:
- "Restart DCaaSS"
