Skip to content

Instantly share code, notes, and snippets.

View h3xagn's full-sized avatar

h3xagn h3xagn

View GitHub Profile
@h3xagn
h3xagn / tags.json
Created June 11, 2023 10:50
Build an OPC UA bridge in Python: https://h3xagn.com
{
"ns=3;s=\"analog data\".\"Level\"": {
"tagName": "analogdata_Level"
},
"ns=3;s=\"analog data\".\"Current\"": {
"tagName": "analogdata_Current"
},
"ns=3;s=\"analog data\".\"Speed\"": {
"tagName": "analogdata_Speed"
},
@h3xagn
h3xagn / opcua-bridge.py
Created June 11, 2023 10:07
Build an OPC UA bridge in Python: https://h3xagn.com
# Import libraries
import asyncio
import json
# Import OPC UA library
from asyncua import Client, Node
# Create handler for subscriptions
class SubscriptionHandler:
@h3xagn
h3xagn / pipenv-offline.txt
Created June 11, 2023 09:51
Running python offline: https://h3xagn.com
# On the PC with internet
# ---------------------------------------------------
# generate the requirements file
pipenv requirements > requirements.txt
# download the packages
pip download -r requirements.txt
# download pipenv
@h3xagn
h3xagn / rabbitmq-consumer.js
Created November 20, 2022 10:27
Streaming logs using RabbitMQ: https://h3xagn.com
// code from RabbitMQ
var wsbroker = "localhost";
var wsport = 15675;
var client = new Paho.MQTT.Client(
wsbroker,
wsport,
"/ws",
"myclientid_" + parseInt(Math.random() * 100, 10)
);
@h3xagn
h3xagn / rabbitmq-producer.py
Created November 20, 2022 10:20
Streaming logs using RabbitMQ: https://h3xagn.com
# import libraries
import time
import logging
from python_logging_rabbitmq import RabbitMQHandler
# set app name
APP_NAME = "app1"
# configure logging
FORMAT = "[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] [%(name)s] %(message)s"
@h3xagn
h3xagn / rabbitmq-consumer.py
Created November 20, 2022 10:20
Streaming logs using RabbitMQ: https://h3xagn.com
# import libraries
import os
import sys
import time
import pika
def main():
# set up connection to RabbitMQ
connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
@h3xagn
h3xagn / extract-sql-03.py
Created August 21, 2022 12:17
Extract data from SQL Server: https://h3xagn.com
# iterate through list of historic databases
for db in list_of_dbs:
logger.info(f"--- Starting export for {db}")
try:
logger.info(f"--- Downloading analog table... ")
query = f"set nocount on; print 'TimeStamp,TagID,TagValue,Quality'; select * from Historian_AnalogTagData"
output_file = f"./data/csv/{site}_{db}_analog.csv"
sqlcmd = (
f'sqlcmd -S {server} -d {db} -U {username} -P {password} -Q "{query}" -s "," -h -1 -W -o "{output_file}"'
@h3xagn
h3xagn / extract-sql-01.py
Created August 21, 2022 12:15
Extract data from SQL Server: https://h3xagn.com
# retrieve tag metadata
query = """
set nocount on;
print 'TagID,TagName,Description,ChangeTimestamp,SourceUniqueTagID,Maximum,Minimum,EngUnits';
select [TagID],[TagName],REPLACE([Description], ',', '') AS [Description],[ChangeTimestamp],[SourceUniqueTagID],[Maximum],[Minimum],[EngUnits]
from TagManager_Tags;
"""
sqlcmd = f'sqlcmd -S {server} -d ProcessDataDB -U {username} -P {password} -Q "{query}" -s "," -h -1 -W -o "./data/{site}_metadata.csv"'
logger.info("-- Getting tag metadata...")
os.system(sqlcmd)
@h3xagn
h3xagn / extract-sql-02.py
Last active August 21, 2022 12:17
Extract data from SQL Server: https://h3xagn.com
# get list of history DBs
# note: check permission of the user to access 'master' database
query = "set nocount on; print 'Database';select name from sys.Databases where name like 'History%'"
sqlcmd = f'sqlcmd -S {server} -d ProcessDataDB -U {username} -P {password} -Q "{query}" -s "," -h -1 -W -o "./data/{site}_dbs.csv"'
logger.info("-- Getting ProcessDataDB History databases...")
os.system(sqlcmd)
# get list of historic databases
df = pd.read_csv(f"./data/{site}_dbs.csv")
logger.info(f"Found {len(df.index)} history DBs.\n")
@h3xagn
h3xagn / main-efergy.py
Created July 7, 2022 19:27
Give your cleverHome one voice: https://h3xagn.com
def GetPowerMeasurement():
"""Get the current power reading from the efergy device"""
try:
url = f"http://www.energyhive.com/mobile_proxy/getCurrentValuesSummary?token={efergy_token}"
response = requests.get(url)
data = response.json()[0]["data"][0]
timestamp = datetime.fromtimestamp(int(list(data.keys())[0]) / 1000)
measurement = list(data.values())[0]
print(f"Power measurement at {timestamp} was {measurement}W.")
return measurement