python – Read Data from a serial port and write to influxdb

I have a energy meter which sends the kWh count periodically every few seconds via a serial port.
To store this data I write the counter value and the calculated average power of the last 10s in a influxdb measurment.

To calculate the power i use a loop that compares the current counter value with the one 10s ago. To avoid that the loop is interrupted by reading the serial interface or sending the data via http i use serial_asyncio and aiohttp.

I am pretty new to Python and got my script running by doing serveral asyncio tutorials, so i am not sure if i mixed some old and new syntax.

The script is working, but I am not happy with a few things.

  1. Is there a better way to pass the counter value from the serial data_received function to my calc_delta function without the use of global?

  2. Am I using asyncio properly? I found different examples using asyncio.ensure_future() or loop.run_until_complete().

  3. Is the overall structure okay, what could i have done better?

import aiohttp
import asyncio
from datetime import datetime
import serial_asyncio
import serial
import time

value = None
last_value = 0
token = "myInfluxdbToken"

class Input(asyncio.Protocol):
    data_buffer = ""

    def connection_made(self, transport):
        self.transport = transport
        print("port opened", transport)

    def data_received(self, data):
        global value

        self.data_buffer += data.decode("utf-8")
        # find counter value in received string
        if "eHZ" in self.data_buffer:
            data_tmp = self.data_buffer.replace("rn", "")
            value_str = data_tmp.partition("1.8.1*255(")(2)(:11)

            if len(value_str) == 11:
                value = float(value_str)
                asyncio.ensure_future(send_data(value, "counter"))
            # Reset the data_buffer!
            self.data_buffer = ""

async def calc_delta():
    global value, last_value
    # calculate counter delta
    while True:
        delta = 0
        if value:
            delta = value - last_value
            last_value = value
        # 10s * 3600s/h * 1000W  Calculates Avg Power of last 10s from kWh delta
        deltaW = delta / 10 * 3600 * 1000
        if deltaW < 50000:
            await send_data(deltaW, "deltaW")
            print(time.perf_counter(), deltaW)
            print(time.perf_counter(), "data invalid")

        await asyncio.sleep(10)

async def send_data(data, tag):
    async with aiohttp.ClientSession() as session:
        async with
            data=f"ehzdata,type={tag} value={data}",
            headers={"Authorization": f"Token {token}"},
        ) as response:
            print("Status:", response.status)

loop = asyncio.get_event_loop()
serial_coro = serial_asyncio.create_serial_connection(
    loop, Input, "/dev/ttyUSB0", baudrate=9600, parity=serial.PARITY_EVEN, bytesize=7
counter_coro = calc_delta()

Write and Publish Guest Post on Uberant. com with Do-Follow Backlink for $2

Write and Publish Guest Post on Uberant. com with Do-Follow Backlink

I will guest post on One do-follow backlink from such a prestigious real website can make a HUGE difference to your rankings!

What you will get:

1. High-Quality Dofollow backlink + Index

2. Up to 400 words article provided.

3. google index

4. High Authority blog

5. I will write the article SEO optimized to improve faster the Google rankings

Note: If you have any questions feel free to contact me.


magento2 – Unable to write output


I’m trying to run the following command

composer show magento/product-community-edition 2.4.* --all | grep -m 1 versions

but I am getting an output of the following:

versions : * 2.4.2

Unable to write output.

show [–all] [–locked] [-i|–installed] [-p|–platform] [-a|–available] [-s|–self] [-N|–name-only] [-P|–path] [-t|–tree] [-l|–latest] [-o|–outdated] [–ignore IGNORE] [-m|–minor-only] [-D|–direct] [–strict] [-f|–format FORMAT] [–no-dev] [–] [] []

I’ve had a look at file/folder permissions and set them again

find var generated vendor pub/static pub/media app/etc -type f -exec chmod u+w {} + && find var generated vendor pub/static pub/media app/etc -type d -exec chmod u+w {} + && chmod u+x bin/magento

I’ve also tried to install the cron again

bin/magento cron:install --force

But alas nothing helps.

macos – Mac Citrix Workspace I can’t write curly braces using an ITA keybaord

I’ve just bought a Macbook Air 2020 (Apple Silicon) with an Italian keyboard.
I work in the game dev industry and in our company, we use Citrix Workspace to use remote PCs.
After setting up the connection with my IT manager I’ve started trying Citrix Workspace and soon I’ve realized that the Mac version of Citrix is really buggy.
The curly braces do not work using any keyboard language on the mac/remote PC.
I’ve tried every possible setting in Citrix Workspace but nothing seems to have an effect.

python – write Function Using While loop

Write a function named test_sqrt that prints a table like the following using a while loop, where “diff” is the absolute value of the difference between my_sqrt(a) and math.sqrt(a).
a = 1 | my_sqrt(a) = 1 | math.sqrt(a) = 1.0 | diff = 0.0
a = 2 | my_sqrt(a) = 1.41421356237 | math.sqrt(a) = 1.41421356237 | diff = 2.22044604925e-16

Here is what I have tried and not working.
import math

def my_sqrt(a):
x = 1
while True:
y = (x + a / x) / 2.0
if y == x:
x = y

return y

def test_sqrt():
while True:
for a in range(1, 9):
approxsqrt = my_sqrt(a)
actualsqrt = math.sqrt(a)
print(“a =”, a,”my_sqrt(a) =”,
approxsqrt,”math.sqrt(a) =”,
actualsqrt,”diff =”,
abs(approxsqrt – actualsqrt))

Google Appscript – CalenderApp, create events from a spreadsheet and write relevant ids back to the spreadsheet

I have a function to create events for field based workers. Eventually I will add this to an onEdit trigger and give the user (centrally based admin worker) some functionality to edit/delete events after they have been created. To do the latter, I believe I will need to be able to isolate the event ID.

Whilst I can write events to a calendar and retrieve the event ID and index of the event just created. I am having difficulty in writing that information back to the spreadsheet (this would be used for edit/delete later in my program).

ws.getRange(4,13,indexes.length,1).setValues(eventIds); allows me to write ids to the spreadsheet but they are not writing to the correct row where the event was created.

How can I use the index stored in const indexes = (); to tell the function the correct row to write the id to. Or is there a better way to achieve this?

Any help would be amazing, I am still very much in the learning stage with Google Appscript. I have tried to research the problem to no avail and I was hoping that the wisdom of others might be able to show me where I am going wrong.

function createEvents(){

const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Sheet Name");
const lr = Math.max.apply(0, ws.getRange('b:b').getValues().map(function (v, i) { if (v != '') { return i } else { return 0 } })) + 1;
const lc = ws.getLastColumn();
const cal = CalendarApp.getCalendarById("myCalId");

const allData = ws.getRange(4,2,lr-3,lc).getValues();
const eventIds = ();
const indexes = ();


const startDate = new Date(r(4));
const sDateHrs = startDate.setHours(8,0);
const endaDate = new Date(r(6));
const eDateHrs = endaDate.setHours(18,0);

if(r(10) === true && r(7) === 'In Progress'){

  var event = cal.createEvent(r(0), new Date(sDateHrs), new Date(eDateHrs), {location: r(1), description: r(3) });  
  var eventId = event.getId();

  eventIds.push((eventId));//pushing event ids to an array to call on later
  indexes.push((idx));//pushing the index of each id to use when writing the ids back to the spreadsheet

  ws.getRange(4,13,indexes.length,1).setValues(eventIds); //places event ids into spreadsheet but not in the correct rows. I want the ids to be written to rows corresponding to the indexes array

  return event;}});