Python Forum
Help with WebSocket reading data from anoter function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with WebSocket reading data from anoter function
#1
hello ,
I'm trying to write a code of reading data from canbus and using websocket to read "Live Data"
the web server is up(I can see the "Server Up" message and also able to connect the port 8765 using websocket client but after connecting I get no data and the canbus reading is still working\printing
I guess something in the veriable setting

this is what I have done:
import can
import datetime
from ftplib import FTP, error_perm
from pathlib import Path

import asyncio
import websockets

RouterIP = "192.168.4.5"
UserName = "FTP_py"
Password = "FTP_12!"

CanBusWorking = False
try:
    bus = can.interface.Bus(channel='can1', bustype='socketcan')
except IOError as e:
    CanBusWorking = False
    print('No such interface!')
except Exception as UnknownError:
    CanBusWorking = False
    print('Unknown - ' + UnknownError)
else:
    CanBusWorking = True

async def hello(websocket, path):
    while True:
        print('Got request from ' + str(websocket.remote_address))
        await websocket.send(LiveData)
async def ReadCanBusData():
    global MotorSpeed
    MotorSpeed = 0
    global MotorTemp
    MotorTemp = 0
    global MotorControllerTemp
    MotorControllerTemp = 0
    global Voltage
    Voltage = 0
    global Current
    Current  = 0
    global SOC
    SOC = 0
    global Insulation
    Insulation = 0
    global TotalNegInsulation
    TotalNegInsulation = 0
    global InsulationParallel
    InsulationParallel = 0
    global Speed
    Speed = 0
    global TotalDistance
    TotalDistance = 0
    global Gear
    Gear = 0
    global BusOn
    BusOn = 00
    global LiveData
    LiveData = "test!no!data!yet"

    while True:
    try:
            message = bus.recv()
        except Exception as e:
            print('error in CanBus!')
        except Exception as e:
            print('Unknown Error in canbus!')
        else:
            if message is None:
                print('TimeOut!')
            else:
                TS = datetime.datetime.now()
                pid_temp = message.arbitration_id
                pid_int = int(pid_temp)
                data_byte = message.data
                data_temp = [f"{byte:02x}" for byte in data_byte]
                Data = ' '.join(data_temp)
                PID = f"{pid_int:08x}"
                PID = PID.upper()
                print(str(TS) + ": " + PID + ": " + Data)
                Speed  = "Speed"
                TotalDistance = "Total"
                Voltage = "Voltage"
                Current = "Current"
                SOC = "SOC"
                global SendTime
                difference = int((TS - SendTime).total_seconds())
                if difference > 5 :
                     LiveData = (TotalDistance, Voltage, Current, SOC)
                     SendTime = datetime.datetime.now()

try:
    start_server = websockets.serve(hello, "10.0.0.100", 8765)
    asyncio.get_event_loop().run_until_complete(start_server) # this for startup the websocket server
except  Exception as e:
    print('Error in  websocket!\n\r  ' + str(e))
else:
    print("Server Started")

if CanBusWorking:
    SendTime = datetime.datetime.now()
    asyncio.get_event_loop().create_task(ReadCanBusData()) # this for create function that works all the time
    asyncio.get_event_loop().run_forever()
when I disable this line "asyncio.get_event_loop().create_task(ReadCanBusData())"
the webserver is wroking and I'm able to red the test data

what am I missing?


I have try to make a simple one :

import asyncio
import websockets
import time
from datetime import datetime

TS = "nothing"


async def hello(websocket, path):
    while True:
        remote_ip = websocket.remote_address
        print('Got request ' + str(remote_ip))
        await websocket.send(TS)


async def time_update():
    while True:
        global TS
        TS = datetime.now().strftime('%d-%m-%y %H-%M-%S-%f')
        print(TS)
        await asyncio.sleep(1.1542)


asyncio.get_event_loop().create_task(time_update()) # this for create function that works all the time

start_server = websockets.serve(hello, "10.0.0.104", 8765)

asyncio.get_event_loop().run_until_complete(start_server) # this for startup the websocket server
print("server started")
asyncio.get_event_loop().run_forever()
and this one is working without any problem , isn't the same?
Thanks ,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function return boolean based on GPIO pin reading caslor 2 1,131 Feb-04-2023, 12:30 PM
Last Post: caslor
  Reading All The RAW Data Inside a PDF NBAComputerMan 4 1,276 Nov-30-2022, 10:54 PM
Last Post: Larz60+
  Reading Data from JSON tpolim008 2 1,032 Sep-27-2022, 06:34 PM
Last Post: Larz60+
  How to send a pong on websocket-client tomtom 0 3,518 Aug-15-2022, 05:58 AM
Last Post: tomtom
  Can't write to .txt after opening websocket gerald 5 1,538 May-03-2022, 12:43 PM
Last Post: deanhystad
  asyncio calls within sync function ( Websocket on_open) orion67 0 1,374 Jan-16-2022, 11:00 AM
Last Post: orion67
  Help reading data from serial RS485 korenron 8 13,608 Nov-14-2021, 06:49 AM
Last Post: korenron
  Fastest Way of Writing/Reading Data JamesA 1 2,139 Jul-27-2021, 03:52 PM
Last Post: Larz60+
  Reading data to python: turn into list or dataframe hhchenfx 2 5,280 Jun-01-2021, 10:28 AM
Last Post: Larz60+
  Reading data from mysql. stsxbel 2 2,164 May-23-2021, 06:56 PM
Last Post: stsxbel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020