Your Digital Media Has Never Looked So Good

 
RokuLyndon

Simple File Networking (update from any web server)

Tue May 11, 2010 4:22 pm

Using BrightAuthor, you can setup the HD210 or HD1010 to download updates from a folder on any web server. This can be a web server on your local network or a remote one on the internet. While you don't have access to the status and management features that are available with a Brightsign Network Account, you can use any web server for updates. The process for updating, explained in more detail below, is very simple:

  1. First, Create a Setup Disk using BrightAuhtor under Tools - > Setup A Unit.
  2. Then, Startup the Brightsign with the Setup Disk
  3. Finally, Publish a presentation, using Simple Networking, and place those files into the web folder

Simple File Networking video
Check out this Simple Networking video for step by step directions.

Tips
Here are some common things to look out for when using simple networking.

  • Mime Types - the autorun.brs file and the firmware update.rok files may need mime types added to your web server. For the autorun.brs, add the .brs extension as text/plain. THe update.rok should be binary.
  • FTP Transfer Binary - if your ftp client is set to a transfer type of ascii or both, you should change it to binary.

  1. Setup A Unit
    In order for the Brightsign to call into your web server for updates, you must use the setup files. If you publish a simple networking project directly to the flash card, the unit will not call into the web server.

    Image

    1. Go to Tools -> Setup A Unit
    2. Select Simple File Networking
    3. Enter the webfolder URL
      In this example, I'm using a dropbox.com account to do web updates.
    4. Choose your connection frequency
    5. Click "Create Setup Files" and save the setup files to a flash card.
  2. Startup Brightsign with Setup Card
    When the Brightsign starts up with a setup card, it will call into the URL provided in the setup file and look for a current-sync.xml file. A current-sync file is created with the setup files, and also each time you publish using simple networking.

    1. Insert Setup Flash Card into Brightsign
    2. Plug the unit into the network (ethernet directly or wifi game adapter or wifi bridge)
    3. Plug the unit into power

  3. Publish Presentation
    If your web server is on the local network, you may be publishing to a folder/drive that's mapped on your desktop. Or, if you're using a service like dropbox, you can publish directly to a public dropbox folder. Otherwise, you'll be publishing to a local directory on your computer, and using an ftp program to transfer the files to your web server.

    Image

    1. Click Publish in BrightAuthor and select Simple Networking
    2. Enter the Web URL you'll be updating from
    3. Enter the local folder you'll be publishing to before transferring the content to the web server
    4. Publish presentation to a local folder
    5. Transfer the published files to your web server directory
 
PeterCassidy
Posts: 17
Joined: Tue Apr 27, 2010 7:33 pm

Re: Simple File Networking (update from any web server)

Wed May 12, 2010 2:57 pm

I'm in the process of implementing Simple Networking for the HD210. What happens if the HD210 polls for the server while a file is being updated on the website? I can see this easily happening with video files which may take say 10 minutes to upload to the website and the HD210 is polling every minute for new updates. Is the HD210 sync process smart enough to suspend updating anytime the website directory is being written to?

Peter Cassidy
 
RokuLyndon

Re: Simple File Networking (update from any web server)

Wed May 12, 2010 3:44 pm

If the files are being updated, then the hash test will fail when the brightsign downloads the file. The brightsign doesn't know the folder is being updated. As soon as the current-sync.xml file is written, and the unit downloads it, it will start trying to grab the changed files in the current-sync.
 
StefanK
Posts: 13
Joined: Wed Jan 13, 2010 7:44 am
Location: Austria

Re: Simple File Networking (update from any web server)

Tue May 18, 2010 8:36 am

Update doesn´t work anymore?
Yesterday everything work ´s fine! Today the HD210 dont update anymore. I made my Layout with BA 2.0.

The HD210 (Firmware 3.2.67)is downloading the Files. On the Webserver I have 4.156.387 Bytes and on the SD-Card 4.165.751 Bytes. SD-Card was formated and prepared with the BA 2.0 --> Tools --> Setup Bright Sign Unit

Files on the SD-Card:
current-sync.xml
autorun.brs
Folders:
Brightsign-dumps --> empty folder
pool --> full with Files named like sha1-9a9a8bf40351ec4cb335fdbb3dded6edb08e277e All 13 files with 4.136.388 Bytes

But the HD210 stays black! He dont reboot or do anything.

Any ideas? :?:
Stefan


current-sync.xml File:
<?xml version="1.0" encoding="utf-8"?>
<sync version="1.0" name="Simple Networking">
  <meta>
    <client>
      <base>http://192.168.2.7/pos/tdot/</base>
      <next>/current-sync.xml</next>
      <event>EVENT</event>
      <error>ERROR</error>
      <deviceerror>DEVICEERROR</deviceerror>
      <devicedownload>DEVICEDOWNLOAD</devicedownload>
      <trafficdownload>TRAFFICDOWNLOAD</trafficdownload>
      <uploadusage>UPLOADUSAGE</uploadusage>
      <nowplaying>NOWPLAYING</nowplaying>
      <getfile>GETFILE</getfile>
      <timezone>GMT+1</timezone>
      <unitName />
      <unitNamingMethod>appendUnitIDToUnitName</unitNamingMethod>
      <unitDescription />
      <timeBetweenNetConnects>60</timeBetweenNetConnects>
      <contentDownloadsRestricted>no</contentDownloadsRestricted>
      <useDHCP>yes</useDHCP>
      <timeServer>time.brightsignnetwork.com</timeServer>
    </client>
    <server>
      <account>ACCOUNT</account>
      <user />
      <password />
      <group>Simple Networking</group>
    </server>
  </meta>
  <files />
</sync>


autorun.brs:

REM
REM autorun-setup - setup file for simple networking
REM January 20, 2010
REM Copyright (c) 2006-2010 Roku, Inc.
REM

Sub Main()

    debugOn = true
    loggingOn = false
   
    RunSetup(debugOn, loggingOn)

    Stop
   
End Sub


Sub RunSetup(debugOn As Boolean, loggingOn As Boolean)

    Setup = newSetup(debugOn, loggingOn)

    setupVersion$ = "3.1.0.4"
    print "setup script version ";setupVersion$;" started"

    modelObject = CreateObject("roDeviceInfo")
    deviceUniqueID$ = modelObject.GetDeviceUniqueId()
    deviceFWVersion$ = modelObject.GetVersion()

    ' create pool directory
    ok = CreateDirectory("pool")

    Setup.SetSystemInfo(setupVersion$, deviceFWVersion$, deviceUniqueID$)

    Setup.networkingActive = Setup.networking.InitializeNetworkDownloads()

    Setup.EventLoop()
   
    return

End Sub


Function newSetup(debugOn As Boolean, loggingOn As Boolean) As Object

    Setup = CreateObject("roAssociativeArray")

    Setup.debugOn = debugOn
   
    Setup.systemTime = CreateObject("roSystemTime")
    Setup.diagnostics = newDiagnostics(debugOn, loggingOn)

    Setup.msgPort = CreateObject("roMessagePort")

    Setup.newNetworking = newNetworking
    Setup.networking = Setup.newNetworking(Setup)
       
    Setup.SetSystemInfo = SetupSetSystemInfo
    Setup.EventLoop = EventLoop

    return Setup

End Function
 

Sub SetupSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.diagnostics.SetSystemInfo(setupVersion$, firmwareVersion$, deviceUniqueID$)
    m.networking.SetSystemInfo(setupVersion$, firmwareVersion$, deviceUniqueID$)

    return

End Sub


Sub EventLoop()

    while true
   
       msg = wait(0, m.msgPort)
      
       if (type(msg) = "roUrlEvent") then
      
            m.networking.URLEvent(msg)
         
       elseif (type(msg) = "roSyncPoolEvent") then
      
            m.networking.PoolEvent(msg)
         
       elseif (type(msg) = "roTimerEvent") then
      
          m.networking.StartSync()
   
       endif

    endwhile

    return

End Sub


REM *******************************************************
REM *******************************************************
REM ***************                    ********************
REM *************** DIAGNOSTICS OBJECT ********************
REM ***************                    ********************
REM *******************************************************
REM *******************************************************

REM
REM construct a new diagnostics BrightScript object
REM
Function newDiagnostics(debugOn As Boolean, loggingOn As Boolean) As Object

    diagnostics = CreateObject("roAssociativeArray")
   
    diagnostics.debug = debugOn
    diagnostics.logging = loggingOn
    diagnostics.setupVersion$ = "unknown"
    diagnostics.firmwareVersion$ = "unknown"
    diagnostics.systemTime = CreateObject("roSystemTime")
   
    diagnostics.PrintDebug = PrintDebug
    diagnostics.PrintTimestamp = PrintTimestamp
    diagnostics.OpenLogFile = OpenLogFile
    diagnostics.CloseLogFile = CloseLogFile
    diagnostics.FlushLogFile = FlushLogFile
    diagnostics.WriteToLog = WriteToLog
    diagnostics.SetSystemInfo = DiagnosticsSetSystemInfo
    diagnostics.RotateLogFiles = RotateLogFiles
    diagnostics.TurnDebugOn = TurnDebugOn
   
    diagnostics.OpenLogFile()

    return diagnostics

End Function


Sub TurnDebugOn()

    m.debug = true
   
    return
   
End Sub


Sub DiagnosticsSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.setupVersion$ = setupVersion$
    m.firmwareVersion$ = firmwareVersion$
    m.deviceUniqueID$ = deviceUniqueID$

    return

End Sub


Sub OpenLogFile()

    m.logFile = 0

    if not m.logging then return

    m.logFileLength = 0

    m.logFile = CreateObject("roReadFile", "log.txt")
    if type(m.logFile) = "roReadFile" then
        m.logFile.SeekToEnd()
        m.logFileLength = m.logFile.CurrentPosition()
        m.logFile = 0
    endif

    m.logFile = CreateObject("roAppendFile", "log.txt")
    if type(m.logFile)<>"roAppendFile" then
        print "unable to open log.txt"
        stop
    endif

    return

End Sub


Sub CloseLogFile()

    if not m.logging then return

    m.logFile.Flush()
    m.logFile = 0

    return

End Sub


Sub FlushLogFile()

    if not m.logging then return

    if m.logFileLength > 1000000 then
        print  "### - Rotate Log Files - ###"
        m.logFile.SendLine("### - Rotate Log Files - ###")
    endif

    m.logFile.Flush()

    if m.logFileLength > 1000000 then
        m.RotateLogFiles()
    endif

    return

End Sub


Sub WriteToLog(eventType$ As String, eventData$ As String, eventResponseCode$ As String, accountName$ As String)

    if not m.logging then return

    if m.debug then print "### write_event"

    ' write out the following info
    '   Timestamp, Device ID, Account Name, Event Type, Event Data, Response Code, Software Version, Firmware Version
    eventDateTime = m.systemTime.GetLocalDateTime()
    eventDataStr$ = eventDateTime + " " + accountName$ + " " + eventType$ + " " + eventData$ + " " + eventResponseCode$ + " recovery_runsetup.brs " + m.setupVersion$ + " " + m.firmwareVersion$
    if m.debug then print "eventDataStr$ = ";eventDataStr$
    m.logFile.SendLine(eventDataStr$)

    m.logFileLength = m.logFileLength + len(eventDataStr$) + 14

    m.FlushLogFile()

    return

End Sub


Sub RotateLogFiles()

    log3 = CreateObject("roReadFile", "log_3.txt")
    if type(log3)="roReadFile" then
        log3 = 0
      DeleteFile("log_3.txt")
    endif

    log2 = CreateObject("roReadFile", "log_2.txt")
    if type(log2)="roReadFile" then
        log2 = 0
        MoveFile("log_2.txt", "log_3.txt")
    endif

    m.logFile = 0
    MoveFile("log.txt", "log_2.txt")

    m.OpenLogFile()

    return

End Sub


Sub PrintDebug(debugStr$ As String)

    if type(m) <> "roAssociativeArray" then stop
   
    if m.debug then

        print debugStr$

        if not m.logging then return

        m.logFile.SendLine(debugStr$)
        m.logFileLength = m.logFileLength + len(debugStr$) + 1
        m.FlushLogFile()

    endif

    return

End Sub


Sub PrintTimestamp()

    eventDateTime = m.systemTime.GetLocalDateTime()
    if m.debug then print eventDateTime.GetString()
    if not m.logging then return
    m.logFile.SendLine(eventDateTime)
    m.FlushLogFile()

    return

End Sub



REM *******************************************************
REM *******************************************************
REM ***************                    ********************
REM *************** NETWORKING OBJECT  ********************
REM ***************                    ********************
REM *******************************************************
REM *******************************************************

REM
REM construct a new networking BrightScript object
REM
Function newNetworking(BSP As Object) As Object

    networking = CreateObject("roAssociativeArray")

    networking.systemTime = m.systemTime
    networking.diagnostics = m.diagnostics
    networking.msgPort = m.msgPort

    networking.InitializeNetworkDownloads = InitializeNetworkDownloads
    networking.StartSync = StartSync
    networking.URLEvent = URLEvent
    networking.PoolEvent = PoolEvent
    networking.GetPoolFilePath = GetPoolFilePath
   
    networking.ClearLegacyRegistryEntries = ClearLegacyRegistryEntries
   
    networking.SendError = SendError
    networking.SendErrorCommon = SendErrorCommon
    networking.SendErrorThenReboot = SendErrorThenReboot
    networking.SendEvent = SendEvent
    networking.SendEventCommon = SendEventCommon
    networking.SendEventThenReboot = SendEventThenReboot
    networking.SetSystemInfo = NetworkingSetSystemInfo
   
    networking.POOL_EVENT_FILE_DOWNLOADED = 1
    networking.POOL_EVENT_FILE_FAILED = -1
    networking.POOL_EVENT_ALL_DOWNLOADED = 2
    networking.POOL_EVENT_ALL_FAILED = -2

    networking.SYNC_ERROR_CANCELLED = -10001
    networking.SYNC_ERROR_CHECKSUM_MISMATCH = -10002
    networking.SYNC_ERROR_EXCEPTION = -10003
    networking.SYNC_ERROR_DISK_ERROR = -10004
    networking.SYNC_ERROR_POOL_UNSATISFIED = -10005

    networking.URL_EVENT_COMPLETE = 1

   du = CreateObject("roStorageInfo", "./")
    networking.cardSizeInMB = du.GetSizeInMegabytes()
    du = 0

    return networking

End Function


Sub ClearLegacyRegistryEntries()

    registrySection = CreateObject("roRegistrySection", "networking")
    if type(registrySection)<>"roRegistrySection" then print "Error: Unable to create roRegistrySection":stop

    registrySection.Delete("next")
    registrySection.Delete("event")
    registrySection.Delete("error")
    registrySection.Delete("deviceerror")
    registrySection.Delete("devicedownload")
    registrySection.Delete("recurl")
    registrySection.Delete("timezone")
    registrySection.Delete("unitName")
    registrySection.Delete("unitNamingMethod")
    registrySection.Delete("unitDescription")
    registrySection.Delete("timeBetweenNetConnects")
    registrySection.Delete("contentDownloadsRestricted")
    registrySection.Delete("contentDownloadRangeStart")
    registrySection.Delete("contentDownloadRangeLength")
    registrySection.Delete("useDHCP")
    registrySection.Delete("staticIPAddress")
    registrySection.Delete("subnetMask")
    registrySection.Delete("gateway")
    registrySection.Delete("broadcast")
    registrySection.Delete("dns1")
    registrySection.Delete("dns2")
    registrySection.Delete("dns3")
    registrySection.Delete("timeServer")
    registrySection.Delete("account")
    registrySection.Delete("user")
    registrySection.Delete("password")
    registrySection.Delete("group")
   
End Sub


Function InitializeNetworkDownloads() As Boolean

   ' Load up the current sync specification so we have it ready
   m.currentSync = CreateObject("roSyncSpec")
   if not m.currentSync.ReadFromFile("current-sync.xml") then
       m.diagnostics.PrintDebug("### No current sync state available")
      stop
   endif

    baseURL$ = m.currentSync.LookupMetadata("client", "base")
   m.nextURL$ = baseURL$ + m.currentSync.LookupMetadata("client", "next")
    m.user$ = m.currentSync.LookupMetadata("server", "user")
    m.password$ = m.currentSync.LookupMetadata("server", "password")
    if m.user$<>"" and m.password$<>"" then
        m.setUserAndPassword = true
    else
        m.setUserAndPassword = false
    endif

    m.ClearLegacyRegistryEntries()
   
' net connect parameters. read from sync spec, write to registry
    timeBetweenNetConnects$ = m.currentSync.LookupMetadata("client", "timeBetweenNetConnects")
    contentDownloadsRestricted = m.currentSync.LookupMetadata("client", "contentDownloadsRestricted")
    contentDownloadRangeStart = m.currentSync.LookupMetadata("client", "contentDownloadRangeStart")
    contentDownloadRangeLength = m.currentSync.LookupMetadata("client", "contentDownloadRangeLength")

    if timeBetweenNetConnects$ = "" then stop

    registrySection = CreateObject("roRegistrySection", "networking")
    if type(registrySection)<>"roRegistrySection" then print "Error: Unable to create roRegistrySection":stop
    registrySection.Write("tbnc", timeBetweenNetConnects$)
    registrySection.Write("cdr", contentDownloadsRestricted)
    registrySection.Write("cdrs", contentDownloadRangeStart)
    registrySection.Write("cdrl", contentDownloadRangeLength)

' network configuration parameters. read from sync spec, set roNetworkConfiguration, write to registry
    nc = CreateObject("roNetworkConfiguration", 0)
    useDHCP = m.currentSync.LookupMetadata("client", "useDHCP")
    if useDHCP = "no" then
        staticIPAddress$ = m.currentSync.LookupMetadata("client", "staticIPAddress")
        subnetMask$ = m.currentSync.LookupMetadata("client", "subnetMask")
        broadcast$ = m.currentSync.LookupMetadata("client", "broadcast")
        gateway$ = m.currentSync.LookupMetadata("client", "gateway")
        dns1$ = m.currentSync.LookupMetadata("client", "dns1")
        dns2$ = m.currentSync.LookupMetadata("client", "dns2")
        dns3$ = m.currentSync.LookupMetadata("client", "dns3")
       
        nc.SetIP4Address(staticIPAddress$)
        nc.SetIP4Netmask(subnetMask$)
        nc.SetIP4Broadcast(broadcast$)
        nc.SetIP4Gateway(gateway$)
        if dns1$ <> "" then nc.AddDNSServer(dns1$)
        if dns2$ <> "" then nc.AddDNSServer(dns2$)
        if dns3$ <> "" then nc.AddDNSServer(dns3$)
       
        registrySection.Write("dhcp", "no")
        registrySection.Write("sip", staticIPAddress$)
        registrySection.Write("sm", subnetMask$)
        registrySection.Write("gw", gateway$)
        registrySection.Write("bc", broadcast$)
        registrySection.Write("d1", dns1$)
        registrySection.Write("d2", dns2$)
        registrySection.Write("d3", dns3$)
    else
        nc.SetDHCP()
        registrySection.Write("dhcp", "yes")
    endif
   
    timeServer$ = m.currentSync.LookupMetadata("client", "timeServer")
    registrySection.Write("ts", timeServer$)
    nc.SetTimeServer(timeServer$)
   
    success = nc.Apply()

' unit name parameters. read from sync spec, write to registry
    unitName$ = m.currentSync.LookupMetadata("client", "unitName")
    unitNamingMethod$ = m.currentSync.LookupMetadata("client", "unitNamingMethod")
    unitDescription$ = m.currentSync.LookupMetadata("client", "unitDescription")

    registrySection.Write("un", unitName$)
    registrySection.Write("unm", unitNamingMethod$)
    registrySection.Write("ud", unitDescription$)

' registry writes complete - flush it   
    registrySection.Flush()

    m.diagnostics.PrintTimestamp()
   m.diagnostics.PrintDebug("### Currently active sync list suggests next URL of " + m.nextURL$)

   if m.nextURL$ = "" then stop

' Check for updates every minute
   m.checkAlarm = CreateObject("roTimer")
   m.checkAlarm.SetPort(m.msgPort)
   m.checkAlarm.SetDate(-1, -1, -1)
   m.checkAlarm.SetTime(-1, -1, 0, 0)
   if not m.checkAlarm.Start() then stop   

    return true

End Function


Sub StartSync()

' Call when you want to start a sync operation

    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### start_sync")
   
   if type(m.syncPool) = "roSyncPool" then
' This should be improved in the future to work out
' whether the sync spec we're currently satisfying
' matches the one that we're currently downloading or
' not.
        m.diagnostics.PrintDebug("### sync already active so we'll let it continue")
      return
   endif

   m.xfer = CreateObject("roUrlTransfer")
   m.xfer.SetPort(m.msgPort)

   ' We've read in our current sync. Talk to the server to get
   ' the next sync. Note that we use the current-sync.xml because
   ' we need to tell the server what we are _currently_ running not
   ' what we might be running at some point in the future.

   m.diagnostics.PrintDebug("### Looking for new sync list from " + m.nextURL$)
   m.xfer.SetUrl(m.nextURL$)
    if m.setUserAndPassword then m.xfer.SetUserAndPassword(m.user$, m.password$)
   m.xfer.SetHeaders(m.currentSync.GetMetadata("server"))
' Add device unique identifier, timezone
    m.xfer.AddHeader("DeviceID", m.deviceUniqueID$)
    m.xfer.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    m.xfer.AddHeader("DeviceSWVersion", "autorun-setup.brs " + m.setupVersion$)
    m.xfer.AddHeader("timezone", m.systemTime.GetTimeZone())

' Add card size
   m.xfer.AddHeader("storage-size", str(m.cardSizeInMB))

   if not m.xfer.AsyncGetToFile("tmp:new-sync.xml") then stop

    return
   
End Sub


' Call when we get a URL event
Sub URLEvent(msg As Object)

    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### url_event")

   if type (m.xfer) <> "roUrlTransfer" then return
   if msg.GetSourceIdentity() = m.xfer.GetIdentity() then
       if msg.GetInt() = m.URL_EVENT_COMPLETE then
          xferInUse = false
          if msg.GetResponseCode() = 200 then
             m.newSync = CreateObject("roSyncSpec")
             if m.newSync.ReadFromFile("tmp:new-sync.xml") then
                    m.diagnostics.PrintDebug("### Server gave us spec: " + m.newSync.GetName())
                readySync = CreateObject("roSyncSpec")
                if readySync.ReadFromFile("ready-sync.xml") then
                   if m.newSync.EqualTo(readySync) then
                            m.diagnostics.PrintDebug("### Server has given us a spec that matches ready-sync. Nothing more to do.")
                      DeleteFile("tmp:new-sync.xml")
                      readySync = 0
                      m.newSync = 0
                      return
                   endif
                endif

' Anything the server has given us supersedes ready-sync.xml so we'd better delete it and cancel its alarm
                DeleteFile("ready-sync.xml")

' Log the start of sync list download
                    m.SendEvent("StartSyncListDownload", m.newSync.GetName(), "")

                m.syncPool = CreateObject("roSyncPool", "pool")
                m.syncPool.SetPort(m.msgPort)
                    m.syncPool.SetMinimumTransferRate(1000,900)
                    if m.setUserAndPassword then m.syncPool.SetUserAndPassword(m.user$, m.password$)
                    m.syncPool.SetHeaders(m.newSync.GetMetadata("server"))
                    m.syncPool.AddHeader("DeviceID", m.deviceUniqueID$)

' implies dodgy XML, or something is already running. could happen if server sends down bad xml.
                if not m.syncPool.AsyncDownload(m.newSync) then
                    m.diagnostics.PrintTimestamp()
                        m.diagnostics.PrintDebug("### AsyncDownload failed: " + m.syncPool.GetFailureReason())
                   m.newSync = 0
                   m.SendError("AsyncDownloadFailure", m.syncPool.GetFailureReason(), "", m.newSync.GetName())
                endif
' implies dodgy XML, or something is already running. could happen if server sends down bad xml.
             else
                 m.diagnostics.PrintDebug("### Failed to read new-sync.xml")
                 m.SendError("Failed to read new-sync.xml", "", "", m.newSync.GetName())
                m.newSync = 0
             endif
          else if msg.GetResponseCode() = 404 then
                m.diagnostics.PrintDebug("### Server has no sync list for us: " + str(msg.GetResponseCode()))
' The server has no new sync for us. That means if we have one lined up then we should destroy it.
             DeleteFile("ready-sync.xml")
          else
    ' retry - server returned something other than a 200 or 404
                m.diagnostics.PrintDebug("### Failed to download sync list.")
                m.SendError("Failed to download sync list", "", str(msg.GetResponseCode()), "")
          endif
       else
          m.diagnostics.PrintDebug("### Progress URL event - we don't know about those.")
       endif

   else
       m.diagnostics.PrintDebug("### url_event from beyond this world: " + str(msg.GetSourceIdentity()) + ", " + str(msg.GetResponseCode()) + ", " + str(msg.GetInt()))
        m.SendError("url_event from beyond this world", "", "", str(msg.GetSourceIdentity()))
   endif
   
   return

End Sub


' Call when we get a sync event
Sub PoolEvent(msg As Object)
    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### pool_event")
   if type(m.syncPool) <> "roSyncPool" then
        m.diagnostics.PrintDebug("### pool_event but we have no object")
      return
   endif
   if msg.GetSourceIdentity() = m.syncPool.GetIdentity() then
      if (msg.GetEvent() = m.POOL_EVENT_FILE_DOWNLOADED) then
            m.diagnostics.PrintDebug("### File downloaded " + msg.GetName())
      elseif (msg.GetEvent() = m.POOL_EVENT_FILE_FAILED) then
            m.diagnostics.PrintDebug("### File failed " + msg.GetName() + ": " + msg.GetFailureReason())
            m.SendError("FileDownloadFailure", msg.GetFailureReason(), str(msg.GetResponseCode()), msg.GetName())
      elseif (msg.GetEvent() = m.POOL_EVENT_ALL_DOWNLOADED) then
            m.diagnostics.PrintDebug("### All downloaded for " + m.newSync.GetName())

' Log the end of sync list download
            m.SendEvent("EndSyncListDownload", m.newSync.GetName(), str(msg.GetResponseCode()))

' Save to current-sync.xml then do cleanup
          if not m.newSync.WriteToFile("current-sync.xml") then stop
            timezone = m.newSync.LookupMetadata("client", "timezone")
            if timezone <> "" then
                m.systemTime.SetTimeZone(timezone)
            endif
         
            m.diagnostics.PrintDebug("### DOWNLOAD COMPLETE")
           
            m.spf = CreateObject("roSyncPoolFiles", "pool", m.newSync)
           
            autorunFile$ = m.GetPoolFilePath("autorun.brs")
            if autorunFile$ = "" then stop

            autoscheduleFile$ = m.GetPoolFilePath("autoschedule.xml")
            if autoscheduleFile$ = "" then stop
           
            resourcesFile$ = m.GetPoolFilePath("resources.txt")

            success = CopyFile(autorunFile$, "autorun.brs")
            if not success then stop
           
            success = CopyFile(autoscheduleFile$, "autoschedule.xml")
            if not success then stop
           
            if resourcesFile$ <> "" then
                success = CopyFile(resourcesFile$, "resources.txt")
                if not success then stop
            endif

            updateFile$ = m.GetPoolFilePath("update.rok")
            if updateFile$ <> "" then
                success = MoveFile(updateFile$, "update.rok")
            endif

            m.SendEventThenReboot("DownloadComplete", m.newSync.GetName(), "")

         DeleteFile("tmp:new-sync.xml")
         m.newSync = 0
         m.syncPool = 0
      elseif (msg.GetEvent() = m.POOL_EVENT_ALL_FAILED) then
            m.diagnostics.PrintDebug("### Sync failed: " + msg.GetFailureReason())
            m.SendError("SyncFailure", msg.GetFailureReason(), str(msg.GetResponseCode()), "")
         m.newSync = 0
         m.syncPool = 0
      endif
   else
        m.diagnostics.PrintDebug("### pool_event from beyond this world: " + str(msg.GetSourceIdentity()))
   endif
   return

End Sub


Function GetPoolFilePath(fileName$ As String) As Object

    return m.spf.GetPoolFilePath(fileName$)
   
End Function


Sub NetworkingSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.setupVersion$ = setupVersion$
    m.firmwareVersion$ = firmwareVersion$
    m.deviceUniqueID$ = deviceUniqueID$

    return

End Sub


Function SendEventCommon(eventURL As Object, eventType$ As String, eventData$ As String, eventResponseCode$ As String) As String

    m.diagnostics.PrintDebug("### send_event")
   
   eventURL.SetUrl(m.event_url$)
    eventURL.AddHeader("account", m.account$)
    eventURL.AddHeader("group", m.group$)
    eventURL.AddHeader("user", m.user$)
    eventURL.AddHeader("password", m.password$)
    eventURL.AddHeader("DeviceID", m.deviceUniqueID$)
    eventURL.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    eventURL.AddHeader("DeviceSWVersion", "recovery_runsetup.brs " + m.setupVersion$)
    eventStr$ = "EventType=" + eventType$ + "&EventData=" + eventData$ + "&ResponseCode=" + eventResponseCode$

    return eventStr$

End Function


Sub SendEvent(eventType$ As String, eventData$ As String, eventResponseCode$ As String)

return

   eventURL = CreateObject("roUrlTransfer")

    eventStr$ = m.SendEventCommon(eventURL, eventType$, eventData$, eventResponseCode$)

   eventURL.AsyncPostFromString(eventStr$)

    m.diagnostics.WriteToLog(eventType$, eventData$, eventResponseCode$, m.account$)

   return

End Sub


Sub SendEventThenReboot(eventType$ As String, eventData$ As String, eventResponseCode$ As String)

a=RebootSystem()
stop

   eventURL = CreateObject("roUrlTransfer")

    eventStr$ = m.SendEventCommon(eventURL, eventType$, eventData$, eventResponseCode$)

    eventPort = CreateObject("roMessagePort")
   eventURL.SetPort(eventPort)
   eventURL.AsyncPostFromString(eventStr$)

    m.diagnostics.WriteToLog(eventType$, eventData$, eventResponseCode$, m.account$)

    unexpectedUrlEventCount = 0

    while true

        msg = wait(10000, eventPort)   ' wait for either a timeout (10 seconds) or a message indicating that the post was complete

        if type(msg) = "rotINT32" then
            m.diagnostics.PrintDebug("### timeout before final event posted")
            ' clear
           a=RebootSystem()
            stop
        else if type(msg) = "roUrlEvent" then
           if msg.GetSourceIdentity() = eventURL.GetIdentity() then
              if msg.GetResponseCode() = 200 then
                    ' clear
                   a=RebootSystem()
                endif
            endif
        endif

        m.diagnostics.PrintDebug("### unexpected url event while waiting to reboot")
        unexpectedUrlEventCount = unexpectedUrlEventCount + 1
        if unexpectedUrlEventCount > 10 then
            m.diagnostics.PrintDebug("### reboot due to too many url events while waiting to reboot")
            ' clear
            a=RebootSystem()
        endif

    endwhile

    return

End Sub


Function SendErrorCommon(errorURL As Object, errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String) As String

    m.diagnostics.PrintDebug("### send_error")
   
   errorURL = CreateObject("roUrlTransfer")
   errorURL.SetUrl(m.error_url$)
    errorURL.AddHeader("account", m.account$)
    errorURL.AddHeader("group", m.group$)
    errorURL.AddHeader("user", m.user$)
    errorURL.AddHeader("password", m.password$)
    errorURL.AddHeader("DeviceID", m.deviceUniqueID$)
    errorURL.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    errorURL.AddHeader("DeviceSWVersion", "recovery_runsetup.bas " + m.setupVersion$)
    errorStr$ = "ErrorType=" + errorType$ + "&FailureReason=" + errorReason$ + "&ResponseCode=" + errorResponseCode$  + "&ErrorData=" + errorData$

    return errorStr$

End Function


Sub SendError(errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String)

return

   errorURL = CreateObject("roUrlTransfer")

    errorStr$ = m.SendErrorCommon(errorURL, errorType$, errorReason$, errorResponseCode$, errorData$)

   if not errorURL.AsyncPostFromString(errorStr$) then stop

   return

End Sub


Sub SendErrorThenReboot(errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String)

a=RebootSystem()
return

   errorURL = CreateObject("roUrlTransfer")

    errorStr$ = m.SendErrorCommon(errorURL, errorType$, errorReason$, errorResponseCode$, errorData$)

    errorPort = CreateObject("roMessagePort")
   errorURL.SetPort(errorPort)
   if not errorURL.AsyncPostFromString(errorStr$) then stop

    unexpectedUrlErrorCount = 0

    while true

        msg = wait(10000, errorPort)   ' wait for either a timeout (10 seconds) or a message indicating that the post was complete

        if type(msg) = "rotINT32" then
            m.diagnostics.PrintDebug("### timeout before final error posted")
            ' clear
           a=RebootSystem()
            stop
        else if type(msg) = "roUrlEvent" then
           if msg.GetSourceIdentity() = errorURL.GetIdentity() then
              if msg.GetResponseCode() = 200 then
                    ' clear
                   a=RebootSystem()
                endif
            endif
        endif

        m.diagnostics.PrintDebug("### unexpected url event while waiting to reboot")
        unexpectedUrlErrorCount = unexpectedUrlErrorCount + 1
        if unexpectedUrlErrorCount > 10 then
            m.diagnostics.PrintDebug("### reboot due to too many url events while waiting to reboot")
            ' clear
            a=RebootSystem()
        endif

    endwhile

    return

End Sub


 
RokuLyndon

Re: Simple File Networking (update from any web server)

Tue May 18, 2010 9:38 am

If you power the unit off and on does it work?
If you're using scheduling, the question is whether the date and time on the unit is wrong, or not getting set.

A simple test would be to publish an update that plays all day all the time. If the unit is still working fine, it will download it and start playing.
 
StefanK
Posts: 13
Joined: Wed Jan 13, 2010 7:44 am
Location: Austria

Re: Simple File Networking (update from any web server)

Tue May 18, 2010 11:12 am

I already use a all time schedule! But it want update the content. I could ping the HD210, I reach the content on the Webserver. All look fine - like yesterday! But today no update works! I tried to setup the SD-Card new. With the provided tool. But nothing happend!
I also tried it serveral times to power off the HD210 - the only thing I get is a black screen. :-(

What happend when I have a all time schedule an the HD210 doesnt reach the timeserver?
 
StefanK
Posts: 13
Joined: Wed Jan 13, 2010 7:44 am
Location: Austria

Re: Simple File Networking (update from any web server)

Wed May 19, 2010 4:44 am

I found the failure.

The published current Sync File produces the failure

example:
  <download>
   <hash method="SHA1">647E9D23B4676FFE5B5EF598D82F7A5B58B19FB6</hash>
   <link>http://192.168.2.7/pos/tdot//TV_today_13_05.jpg</link>
   <name>TV_today_13_05.jpg</name>
   <size>805080</size>


The Publisher add automatical and second slash!

In the tool "Bright Sign Unit Setup" the Example for the Network is eg. http://brightsign.com/files/
BUT
when you want to Publish the Project and you use the same URL for the Fields "Web Folder Url" like in the Setup tool the Bright Autor 2.0 produces a Failure! because you get a second slash at the end! Here you have to use eg http://brightsign.com/files

You should change this behaviour!

br
Stefan
 
RokuLyndon

Re: Simple File Networking (update from any web server)

Wed May 19, 2010 10:17 am

And, that second slash causes your web server to fail?

It must be that some servers have no problem with the extra slash. That same extra slash works fine for me and many others. But, you are the second user to have mentioned that the extra slash caused a problem with their server. I will log a bug on this.
 
StefanK
Posts: 13
Joined: Wed Jan 13, 2010 7:44 am
Location: Austria

Re: Simple File Networking (update from any web server)

Thu May 20, 2010 12:08 am

I changed it and now it works great. I don´t know which server we have in detail. The website is made with TYPO3, maybe the info helps you.

Greets
Stefan
 
goonsniper
Posts: 2
Joined: Thu Jun 10, 2010 8:04 am

Re: Simple File Networking (update from any web server)

Thu Jun 10, 2010 8:06 am

RokuLyndon

Does that dropbox url actually work for you? Dropbox says you can't link to your public folder, only directly to a file inside it.

Thanks
 
RokuLyndon

Re: Simple File Networking (update from any web server)

Thu Jun 10, 2010 9:21 am

Yes, it does...

What you can do is rightclick on a file inside a public folder, and get the URL, then delete the file from the URL, and now you have the folder link that you need to use. I've used it several times.
 
goonsniper
Posts: 2
Joined: Thu Jun 10, 2010 8:04 am

Re: Simple File Networking (update from any web server)

Thu Jun 10, 2010 9:39 am

 
RokuLyndon

Re: Simple File Networking (update from any web server)

Thu Jun 10, 2010 10:42 am

You can't go to the URL directly in your browser, but you can use it for setup with simple networking, and for publishing for simple networking.
 
rajkob
Posts: 1
Joined: Sat Jun 12, 2010 2:31 am

Re: Simple File Networking (update from any web server)

Sat Jun 12, 2010 2:43 am

I have problem with RokuHD 1010. I did everything as instructed in video above (i am using HFS on local network) but my roku wont update . I can se him on network i can ping him but it wont update.

Here is my current-sync

<?xml version="1.0" encoding="utf-8"?>
<sync version="1.0" name="Simple Networking">
  <meta>
    <client>
      <base>http://10.2.20.98:100/final/</base>
      <next>/current-sync.xml</next>
      <event>EVENT</event>
      <error>ERROR</error>
      <deviceerror>DEVICEERROR</deviceerror>
      <devicedownload>DEVICEDOWNLOAD</devicedownload>
      <trafficdownload>TRAFFICDOWNLOAD</trafficdownload>
      <uploadusage>UPLOADUSAGE</uploadusage>
      <nowplaying>NOWPLAYING</nowplaying>
      <getfile>GETFILE</getfile>
      <timezone>CET</timezone>
      <unitName />
      <unitNamingMethod>appendUnitIDToUnitName</unitNamingMethod>
      <unitDescription />
      <timeBetweenNetConnects>60</timeBetweenNetConnects>
      <contentDownloadsRestricted>no</contentDownloadsRestricted>
      <useDHCP>yes</useDHCP>
      <timeServer>time.brightsignnetwork.com</timeServer>
    </client>
    <server>
      <account>ACCOUNT</account>
      <user />
      <password />
      <group>Simple Networking</group>
    </server>
  </meta>
  <files />
</sync>


and my autorun.brs

REM
REM autorun-setup - setup file for simple networking
REM January 20, 2010
REM Copyright (c) 2006-2010 Roku, Inc.
REM

Sub Main()

    debugOn = true
    loggingOn = false
   
    RunSetup(debugOn, loggingOn)

    Stop
   
End Sub


Sub RunSetup(debugOn As Boolean, loggingOn As Boolean)

    Setup = newSetup(debugOn, loggingOn)

    setupVersion$ = "3.1.0.4"
    print "setup script version ";setupVersion$;" started"

    modelObject = CreateObject("roDeviceInfo")
    deviceUniqueID$ = modelObject.GetDeviceUniqueId()
    deviceFWVersion$ = modelObject.GetVersion()

    ' create pool directory
    ok = CreateDirectory("pool")

    Setup.SetSystemInfo(setupVersion$, deviceFWVersion$, deviceUniqueID$)

    Setup.networkingActive = Setup.networking.InitializeNetworkDownloads()

    Setup.EventLoop()
   
    return

End Sub


Function newSetup(debugOn As Boolean, loggingOn As Boolean) As Object

    Setup = CreateObject("roAssociativeArray")

    Setup.debugOn = debugOn
   
    Setup.systemTime = CreateObject("roSystemTime")
    Setup.diagnostics = newDiagnostics(debugOn, loggingOn)

    Setup.msgPort = CreateObject("roMessagePort")

    Setup.newNetworking = newNetworking
    Setup.networking = Setup.newNetworking(Setup)
       
    Setup.SetSystemInfo = SetupSetSystemInfo
    Setup.EventLoop = EventLoop

    return Setup

End Function
 

Sub SetupSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.diagnostics.SetSystemInfo(setupVersion$, firmwareVersion$, deviceUniqueID$)
    m.networking.SetSystemInfo(setupVersion$, firmwareVersion$, deviceUniqueID$)

    return

End Sub


Sub EventLoop()

    while true
   
       msg = wait(0, m.msgPort)
      
       if (type(msg) = "roUrlEvent") then
      
            m.networking.URLEvent(msg)
         
       elseif (type(msg) = "roSyncPoolEvent") then
      
            m.networking.PoolEvent(msg)
         
       elseif (type(msg) = "roTimerEvent") then
      
          m.networking.StartSync()
   
       endif

    endwhile

    return

End Sub


REM *******************************************************
REM *******************************************************
REM ***************                    ********************
REM *************** DIAGNOSTICS OBJECT ********************
REM ***************                    ********************
REM *******************************************************
REM *******************************************************

REM
REM construct a new diagnostics BrightScript object
REM
Function newDiagnostics(debugOn As Boolean, loggingOn As Boolean) As Object

    diagnostics = CreateObject("roAssociativeArray")
   
    diagnostics.debug = debugOn
    diagnostics.logging = loggingOn
    diagnostics.setupVersion$ = "unknown"
    diagnostics.firmwareVersion$ = "unknown"
    diagnostics.systemTime = CreateObject("roSystemTime")
   
    diagnostics.PrintDebug = PrintDebug
    diagnostics.PrintTimestamp = PrintTimestamp
    diagnostics.OpenLogFile = OpenLogFile
    diagnostics.CloseLogFile = CloseLogFile
    diagnostics.FlushLogFile = FlushLogFile
    diagnostics.WriteToLog = WriteToLog
    diagnostics.SetSystemInfo = DiagnosticsSetSystemInfo
    diagnostics.RotateLogFiles = RotateLogFiles
    diagnostics.TurnDebugOn = TurnDebugOn
   
    diagnostics.OpenLogFile()

    return diagnostics

End Function


Sub TurnDebugOn()

    m.debug = true
   
    return
   
End Sub


Sub DiagnosticsSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.setupVersion$ = setupVersion$
    m.firmwareVersion$ = firmwareVersion$
    m.deviceUniqueID$ = deviceUniqueID$

    return

End Sub


Sub OpenLogFile()

    m.logFile = 0

    if not m.logging then return

    m.logFileLength = 0

    m.logFile = CreateObject("roReadFile", "log.txt")
    if type(m.logFile) = "roReadFile" then
        m.logFile.SeekToEnd()
        m.logFileLength = m.logFile.CurrentPosition()
        m.logFile = 0
    endif

    m.logFile = CreateObject("roAppendFile", "log.txt")
    if type(m.logFile)<>"roAppendFile" then
        print "unable to open log.txt"
        stop
    endif

    return

End Sub


Sub CloseLogFile()

    if not m.logging then return

    m.logFile.Flush()
    m.logFile = 0

    return

End Sub


Sub FlushLogFile()

    if not m.logging then return

    if m.logFileLength > 1000000 then
        print  "### - Rotate Log Files - ###"
        m.logFile.SendLine("### - Rotate Log Files - ###")
    endif

    m.logFile.Flush()

    if m.logFileLength > 1000000 then
        m.RotateLogFiles()
    endif

    return

End Sub


Sub WriteToLog(eventType$ As String, eventData$ As String, eventResponseCode$ As String, accountName$ As String)

    if not m.logging then return

    if m.debug then print "### write_event"

    ' write out the following info
    '   Timestamp, Device ID, Account Name, Event Type, Event Data, Response Code, Software Version, Firmware Version
    eventDateTime = m.systemTime.GetLocalDateTime()
    eventDataStr$ = eventDateTime + " " + accountName$ + " " + eventType$ + " " + eventData$ + " " + eventResponseCode$ + " recovery_runsetup.brs " + m.setupVersion$ + " " + m.firmwareVersion$
    if m.debug then print "eventDataStr$ = ";eventDataStr$
    m.logFile.SendLine(eventDataStr$)

    m.logFileLength = m.logFileLength + len(eventDataStr$) + 14

    m.FlushLogFile()

    return

End Sub


Sub RotateLogFiles()

    log3 = CreateObject("roReadFile", "log_3.txt")
    if type(log3)="roReadFile" then
        log3 = 0
      DeleteFile("log_3.txt")
    endif

    log2 = CreateObject("roReadFile", "log_2.txt")
    if type(log2)="roReadFile" then
        log2 = 0
        MoveFile("log_2.txt", "log_3.txt")
    endif

    m.logFile = 0
    MoveFile("log.txt", "log_2.txt")

    m.OpenLogFile()

    return

End Sub


Sub PrintDebug(debugStr$ As String)

    if type(m) <> "roAssociativeArray" then stop
   
    if m.debug then

        print debugStr$

        if not m.logging then return

        m.logFile.SendLine(debugStr$)
        m.logFileLength = m.logFileLength + len(debugStr$) + 1
        m.FlushLogFile()

    endif

    return

End Sub


Sub PrintTimestamp()

    eventDateTime = m.systemTime.GetLocalDateTime()
    if m.debug then print eventDateTime.GetString()
    if not m.logging then return
    m.logFile.SendLine(eventDateTime)
    m.FlushLogFile()

    return

End Sub



REM *******************************************************
REM *******************************************************
REM ***************                    ********************
REM *************** NETWORKING OBJECT  ********************
REM ***************                    ********************
REM *******************************************************
REM *******************************************************

REM
REM construct a new networking BrightScript object
REM
Function newNetworking(BSP As Object) As Object

    networking = CreateObject("roAssociativeArray")

    networking.systemTime = m.systemTime
    networking.diagnostics = m.diagnostics
    networking.msgPort = m.msgPort

    networking.InitializeNetworkDownloads = InitializeNetworkDownloads
    networking.StartSync = StartSync
    networking.URLEvent = URLEvent
    networking.PoolEvent = PoolEvent
    networking.GetPoolFilePath = GetPoolFilePath
   
    networking.ClearLegacyRegistryEntries = ClearLegacyRegistryEntries
   
    networking.SendError = SendError
    networking.SendErrorCommon = SendErrorCommon
    networking.SendErrorThenReboot = SendErrorThenReboot
    networking.SendEvent = SendEvent
    networking.SendEventCommon = SendEventCommon
    networking.SendEventThenReboot = SendEventThenReboot
    networking.SetSystemInfo = NetworkingSetSystemInfo
   
    networking.POOL_EVENT_FILE_DOWNLOADED = 1
    networking.POOL_EVENT_FILE_FAILED = -1
    networking.POOL_EVENT_ALL_DOWNLOADED = 2
    networking.POOL_EVENT_ALL_FAILED = -2

    networking.SYNC_ERROR_CANCELLED = -10001
    networking.SYNC_ERROR_CHECKSUM_MISMATCH = -10002
    networking.SYNC_ERROR_EXCEPTION = -10003
    networking.SYNC_ERROR_DISK_ERROR = -10004
    networking.SYNC_ERROR_POOL_UNSATISFIED = -10005

    networking.URL_EVENT_COMPLETE = 1

   du = CreateObject("roStorageInfo", "./")
    networking.cardSizeInMB = du.GetSizeInMegabytes()
    du = 0

    return networking

End Function


Sub ClearLegacyRegistryEntries()

    registrySection = CreateObject("roRegistrySection", "networking")
    if type(registrySection)<>"roRegistrySection" then print "Error: Unable to create roRegistrySection":stop

    registrySection.Delete("next")
    registrySection.Delete("event")
    registrySection.Delete("error")
    registrySection.Delete("deviceerror")
    registrySection.Delete("devicedownload")
    registrySection.Delete("recurl")
    registrySection.Delete("timezone")
    registrySection.Delete("unitName")
    registrySection.Delete("unitNamingMethod")
    registrySection.Delete("unitDescription")
    registrySection.Delete("timeBetweenNetConnects")
    registrySection.Delete("contentDownloadsRestricted")
    registrySection.Delete("contentDownloadRangeStart")
    registrySection.Delete("contentDownloadRangeLength")
    registrySection.Delete("useDHCP")
    registrySection.Delete("staticIPAddress")
    registrySection.Delete("subnetMask")
    registrySection.Delete("gateway")
    registrySection.Delete("broadcast")
    registrySection.Delete("dns1")
    registrySection.Delete("dns2")
    registrySection.Delete("dns3")
    registrySection.Delete("timeServer")
    registrySection.Delete("account")
    registrySection.Delete("user")
    registrySection.Delete("password")
    registrySection.Delete("group")
   
End Sub


Function InitializeNetworkDownloads() As Boolean

   ' Load up the current sync specification so we have it ready
   m.currentSync = CreateObject("roSyncSpec")
   if not m.currentSync.ReadFromFile("current-sync.xml") then
       m.diagnostics.PrintDebug("### No current sync state available")
      stop
   endif

    baseURL$ = m.currentSync.LookupMetadata("client", "base")
   m.nextURL$ = baseURL$ + m.currentSync.LookupMetadata("client", "next")
    m.user$ = m.currentSync.LookupMetadata("server", "user")
    m.password$ = m.currentSync.LookupMetadata("server", "password")
    if m.user$<>"" and m.password$<>"" then
        m.setUserAndPassword = true
    else
        m.setUserAndPassword = false
    endif

    m.ClearLegacyRegistryEntries()
   
' net connect parameters. read from sync spec, write to registry
    timeBetweenNetConnects$ = m.currentSync.LookupMetadata("client", "timeBetweenNetConnects")
    contentDownloadsRestricted = m.currentSync.LookupMetadata("client", "contentDownloadsRestricted")
    contentDownloadRangeStart = m.currentSync.LookupMetadata("client", "contentDownloadRangeStart")
    contentDownloadRangeLength = m.currentSync.LookupMetadata("client", "contentDownloadRangeLength")

    if timeBetweenNetConnects$ = "" then stop

    registrySection = CreateObject("roRegistrySection", "networking")
    if type(registrySection)<>"roRegistrySection" then print "Error: Unable to create roRegistrySection":stop
    registrySection.Write("tbnc", timeBetweenNetConnects$)
    registrySection.Write("cdr", contentDownloadsRestricted)
    registrySection.Write("cdrs", contentDownloadRangeStart)
    registrySection.Write("cdrl", contentDownloadRangeLength)

' network configuration parameters. read from sync spec, set roNetworkConfiguration, write to registry
    nc = CreateObject("roNetworkConfiguration", 0)
    useDHCP = m.currentSync.LookupMetadata("client", "useDHCP")
    if useDHCP = "no" then
        staticIPAddress$ = m.currentSync.LookupMetadata("client", "staticIPAddress")
        subnetMask$ = m.currentSync.LookupMetadata("client", "subnetMask")
        broadcast$ = m.currentSync.LookupMetadata("client", "broadcast")
        gateway$ = m.currentSync.LookupMetadata("client", "gateway")
        dns1$ = m.currentSync.LookupMetadata("client", "dns1")
        dns2$ = m.currentSync.LookupMetadata("client", "dns2")
        dns3$ = m.currentSync.LookupMetadata("client", "dns3")
       
        nc.SetIP4Address(staticIPAddress$)
        nc.SetIP4Netmask(subnetMask$)
        nc.SetIP4Broadcast(broadcast$)
        nc.SetIP4Gateway(gateway$)
        if dns1$ <> "" then nc.AddDNSServer(dns1$)
        if dns2$ <> "" then nc.AddDNSServer(dns2$)
        if dns3$ <> "" then nc.AddDNSServer(dns3$)
       
        registrySection.Write("dhcp", "no")
        registrySection.Write("sip", staticIPAddress$)
        registrySection.Write("sm", subnetMask$)
        registrySection.Write("gw", gateway$)
        registrySection.Write("bc", broadcast$)
        registrySection.Write("d1", dns1$)
        registrySection.Write("d2", dns2$)
        registrySection.Write("d3", dns3$)
    else
        nc.SetDHCP()
        registrySection.Write("dhcp", "yes")
    endif
   
    timeServer$ = m.currentSync.LookupMetadata("client", "timeServer")
    registrySection.Write("ts", timeServer$)
    nc.SetTimeServer(timeServer$)
   
    success = nc.Apply()

' unit name parameters. read from sync spec, write to registry
    unitName$ = m.currentSync.LookupMetadata("client", "unitName")
    unitNamingMethod$ = m.currentSync.LookupMetadata("client", "unitNamingMethod")
    unitDescription$ = m.currentSync.LookupMetadata("client", "unitDescription")

    registrySection.Write("un", unitName$)
    registrySection.Write("unm", unitNamingMethod$)
    registrySection.Write("ud", unitDescription$)

' registry writes complete - flush it   
    registrySection.Flush()

    m.diagnostics.PrintTimestamp()
   m.diagnostics.PrintDebug("### Currently active sync list suggests next URL of " + m.nextURL$)

   if m.nextURL$ = "" then stop

' Check for updates every minute
   m.checkAlarm = CreateObject("roTimer")
   m.checkAlarm.SetPort(m.msgPort)
   m.checkAlarm.SetDate(-1, -1, -1)
   m.checkAlarm.SetTime(-1, -1, 0, 0)
   if not m.checkAlarm.Start() then stop   

    return true

End Function


Sub StartSync()

' Call when you want to start a sync operation

    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### start_sync")
   
   if type(m.syncPool) = "roSyncPool" then
' This should be improved in the future to work out
' whether the sync spec we're currently satisfying
' matches the one that we're currently downloading or
' not.
        m.diagnostics.PrintDebug("### sync already active so we'll let it continue")
      return
   endif

   m.xfer = CreateObject("roUrlTransfer")
   m.xfer.SetPort(m.msgPort)

   ' We've read in our current sync. Talk to the server to get
   ' the next sync. Note that we use the current-sync.xml because
   ' we need to tell the server what we are _currently_ running not
   ' what we might be running at some point in the future.

   m.diagnostics.PrintDebug("### Looking for new sync list from " + m.nextURL$)
   m.xfer.SetUrl(m.nextURL$)
    if m.setUserAndPassword then m.xfer.SetUserAndPassword(m.user$, m.password$)
   m.xfer.SetHeaders(m.currentSync.GetMetadata("server"))
' Add device unique identifier, timezone
    m.xfer.AddHeader("DeviceID", m.deviceUniqueID$)
    m.xfer.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    m.xfer.AddHeader("DeviceSWVersion", "autorun-setup.brs " + m.setupVersion$)
    m.xfer.AddHeader("timezone", m.systemTime.GetTimeZone())

' Add card size
   m.xfer.AddHeader("storage-size", str(m.cardSizeInMB))

   if not m.xfer.AsyncGetToFile("tmp:new-sync.xml") then stop

    return
   
End Sub


' Call when we get a URL event
Sub URLEvent(msg As Object)

    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### url_event")

   if type (m.xfer) <> "roUrlTransfer" then return
   if msg.GetSourceIdentity() = m.xfer.GetIdentity() then
       if msg.GetInt() = m.URL_EVENT_COMPLETE then
          xferInUse = false
          if msg.GetResponseCode() = 200 then
             m.newSync = CreateObject("roSyncSpec")
             if m.newSync.ReadFromFile("tmp:new-sync.xml") then
                    m.diagnostics.PrintDebug("### Server gave us spec: " + m.newSync.GetName())
                readySync = CreateObject("roSyncSpec")
                if readySync.ReadFromFile("ready-sync.xml") then
                   if m.newSync.EqualTo(readySync) then
                            m.diagnostics.PrintDebug("### Server has given us a spec that matches ready-sync. Nothing more to do.")
                      DeleteFile("tmp:new-sync.xml")
                      readySync = 0
                      m.newSync = 0
                      return
                   endif
                endif

' Anything the server has given us supersedes ready-sync.xml so we'd better delete it and cancel its alarm
                DeleteFile("ready-sync.xml")

' Log the start of sync list download
                    m.SendEvent("StartSyncListDownload", m.newSync.GetName(), "")

                m.syncPool = CreateObject("roSyncPool", "pool")
                m.syncPool.SetPort(m.msgPort)
                    m.syncPool.SetMinimumTransferRate(1000,900)
                    if m.setUserAndPassword then m.syncPool.SetUserAndPassword(m.user$, m.password$)
                    m.syncPool.SetHeaders(m.newSync.GetMetadata("server"))
                    m.syncPool.AddHeader("DeviceID", m.deviceUniqueID$)

' implies dodgy XML, or something is already running. could happen if server sends down bad xml.
                if not m.syncPool.AsyncDownload(m.newSync) then
                    m.diagnostics.PrintTimestamp()
                        m.diagnostics.PrintDebug("### AsyncDownload failed: " + m.syncPool.GetFailureReason())
                   m.newSync = 0
                   m.SendError("AsyncDownloadFailure", m.syncPool.GetFailureReason(), "", m.newSync.GetName())
                endif
' implies dodgy XML, or something is already running. could happen if server sends down bad xml.
             else
                 m.diagnostics.PrintDebug("### Failed to read new-sync.xml")
                 m.SendError("Failed to read new-sync.xml", "", "", m.newSync.GetName())
                m.newSync = 0
             endif
          else if msg.GetResponseCode() = 404 then
                m.diagnostics.PrintDebug("### Server has no sync list for us: " + str(msg.GetResponseCode()))
' The server has no new sync for us. That means if we have one lined up then we should destroy it.
             DeleteFile("ready-sync.xml")
          else
    ' retry - server returned something other than a 200 or 404
                m.diagnostics.PrintDebug("### Failed to download sync list.")
                m.SendError("Failed to download sync list", "", str(msg.GetResponseCode()), "")
          endif
       else
          m.diagnostics.PrintDebug("### Progress URL event - we don't know about those.")
       endif

   else
       m.diagnostics.PrintDebug("### url_event from beyond this world: " + str(msg.GetSourceIdentity()) + ", " + str(msg.GetResponseCode()) + ", " + str(msg.GetInt()))
        m.SendError("url_event from beyond this world", "", "", str(msg.GetSourceIdentity()))
   endif
   
   return

End Sub


' Call when we get a sync event
Sub PoolEvent(msg As Object)
    m.diagnostics.PrintTimestamp()
    m.diagnostics.PrintDebug("### pool_event")
   if type(m.syncPool) <> "roSyncPool" then
        m.diagnostics.PrintDebug("### pool_event but we have no object")
      return
   endif
   if msg.GetSourceIdentity() = m.syncPool.GetIdentity() then
      if (msg.GetEvent() = m.POOL_EVENT_FILE_DOWNLOADED) then
            m.diagnostics.PrintDebug("### File downloaded " + msg.GetName())
      elseif (msg.GetEvent() = m.POOL_EVENT_FILE_FAILED) then
            m.diagnostics.PrintDebug("### File failed " + msg.GetName() + ": " + msg.GetFailureReason())
            m.SendError("FileDownloadFailure", msg.GetFailureReason(), str(msg.GetResponseCode()), msg.GetName())
      elseif (msg.GetEvent() = m.POOL_EVENT_ALL_DOWNLOADED) then
            m.diagnostics.PrintDebug("### All downloaded for " + m.newSync.GetName())

' Log the end of sync list download
            m.SendEvent("EndSyncListDownload", m.newSync.GetName(), str(msg.GetResponseCode()))

' Save to current-sync.xml then do cleanup
          if not m.newSync.WriteToFile("current-sync.xml") then stop
            timezone = m.newSync.LookupMetadata("client", "timezone")
            if timezone <> "" then
                m.systemTime.SetTimeZone(timezone)
            endif
         
            m.diagnostics.PrintDebug("### DOWNLOAD COMPLETE")
           
            m.spf = CreateObject("roSyncPoolFiles", "pool", m.newSync)
           
            autorunFile$ = m.GetPoolFilePath("autorun.brs")
            if autorunFile$ = "" then stop

            autoscheduleFile$ = m.GetPoolFilePath("autoschedule.xml")
            if autoscheduleFile$ = "" then stop
           
            resourcesFile$ = m.GetPoolFilePath("resources.txt")

            success = CopyFile(autorunFile$, "autorun.brs")
            if not success then stop
           
            success = CopyFile(autoscheduleFile$, "autoschedule.xml")
            if not success then stop
           
            if resourcesFile$ <> "" then
                success = CopyFile(resourcesFile$, "resources.txt")
                if not success then stop
            endif

            updateFile$ = m.GetPoolFilePath("update.rok")
            if updateFile$ <> "" then
                success = MoveFile(updateFile$, "update.rok")
            endif

            m.SendEventThenReboot("DownloadComplete", m.newSync.GetName(), "")

         DeleteFile("tmp:new-sync.xml")
         m.newSync = 0
         m.syncPool = 0
      elseif (msg.GetEvent() = m.POOL_EVENT_ALL_FAILED) then
            m.diagnostics.PrintDebug("### Sync failed: " + msg.GetFailureReason())
            m.SendError("SyncFailure", msg.GetFailureReason(), str(msg.GetResponseCode()), "")
         m.newSync = 0
         m.syncPool = 0
      endif
   else
        m.diagnostics.PrintDebug("### pool_event from beyond this world: " + str(msg.GetSourceIdentity()))
   endif
   return

End Sub


Function GetPoolFilePath(fileName$ As String) As Object

    return m.spf.GetPoolFilePath(fileName$)
   
End Function


Sub NetworkingSetSystemInfo(setupVersion$ As String, firmwareVersion$ As String, deviceUniqueID$ As String)

    m.setupVersion$ = setupVersion$
    m.firmwareVersion$ = firmwareVersion$
    m.deviceUniqueID$ = deviceUniqueID$

    return

End Sub


Function SendEventCommon(eventURL As Object, eventType$ As String, eventData$ As String, eventResponseCode$ As String) As String

    m.diagnostics.PrintDebug("### send_event")
   
   eventURL.SetUrl(m.event_url$)
    eventURL.AddHeader("account", m.account$)
    eventURL.AddHeader("group", m.group$)
    eventURL.AddHeader("user", m.user$)
    eventURL.AddHeader("password", m.password$)
    eventURL.AddHeader("DeviceID", m.deviceUniqueID$)
    eventURL.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    eventURL.AddHeader("DeviceSWVersion", "recovery_runsetup.brs " + m.setupVersion$)
    eventStr$ = "EventType=" + eventType$ + "&EventData=" + eventData$ + "&ResponseCode=" + eventResponseCode$

    return eventStr$

End Function


Sub SendEvent(eventType$ As String, eventData$ As String, eventResponseCode$ As String)

return

   eventURL = CreateObject("roUrlTransfer")

    eventStr$ = m.SendEventCommon(eventURL, eventType$, eventData$, eventResponseCode$)

   eventURL.AsyncPostFromString(eventStr$)

    m.diagnostics.WriteToLog(eventType$, eventData$, eventResponseCode$, m.account$)

   return

End Sub


Sub SendEventThenReboot(eventType$ As String, eventData$ As String, eventResponseCode$ As String)

a=RebootSystem()
stop

   eventURL = CreateObject("roUrlTransfer")

    eventStr$ = m.SendEventCommon(eventURL, eventType$, eventData$, eventResponseCode$)

    eventPort = CreateObject("roMessagePort")
   eventURL.SetPort(eventPort)
   eventURL.AsyncPostFromString(eventStr$)

    m.diagnostics.WriteToLog(eventType$, eventData$, eventResponseCode$, m.account$)

    unexpectedUrlEventCount = 0

    while true

        msg = wait(10000, eventPort)   ' wait for either a timeout (10 seconds) or a message indicating that the post was complete

        if type(msg) = "rotINT32" then
            m.diagnostics.PrintDebug("### timeout before final event posted")
            ' clear
           a=RebootSystem()
            stop
        else if type(msg) = "roUrlEvent" then
           if msg.GetSourceIdentity() = eventURL.GetIdentity() then
              if msg.GetResponseCode() = 200 then
                    ' clear
                   a=RebootSystem()
                endif
            endif
        endif

        m.diagnostics.PrintDebug("### unexpected url event while waiting to reboot")
        unexpectedUrlEventCount = unexpectedUrlEventCount + 1
        if unexpectedUrlEventCount > 10 then
            m.diagnostics.PrintDebug("### reboot due to too many url events while waiting to reboot")
            ' clear
            a=RebootSystem()
        endif

    endwhile

    return

End Sub


Function SendErrorCommon(errorURL As Object, errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String) As String

    m.diagnostics.PrintDebug("### send_error")
   
   errorURL = CreateObject("roUrlTransfer")
   errorURL.SetUrl(m.error_url$)
    errorURL.AddHeader("account", m.account$)
    errorURL.AddHeader("group", m.group$)
    errorURL.AddHeader("user", m.user$)
    errorURL.AddHeader("password", m.password$)
    errorURL.AddHeader("DeviceID", m.deviceUniqueID$)
    errorURL.AddHeader("DeviceFWVersion", m.firmwareVersion$)
    errorURL.AddHeader("DeviceSWVersion", "recovery_runsetup.bas " + m.setupVersion$)
    errorStr$ = "ErrorType=" + errorType$ + "&FailureReason=" + errorReason$ + "&ResponseCode=" + errorResponseCode$  + "&ErrorData=" + errorData$

    return errorStr$

End Function


Sub SendError(errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String)

return

   errorURL = CreateObject("roUrlTransfer")

    errorStr$ = m.SendErrorCommon(errorURL, errorType$, errorReason$, errorResponseCode$, errorData$)

   if not errorURL.AsyncPostFromString(errorStr$) then stop

   return

End Sub


Sub SendErrorThenReboot(errorType$ As String, errorReason$ As String, errorResponseCode$ As String, errorData$ As String)

a=RebootSystem()
return

   errorURL = CreateObject("roUrlTransfer")

    errorStr$ = m.SendErrorCommon(errorURL, errorType$, errorReason$, errorResponseCode$, errorData$)

    errorPort = CreateObject("roMessagePort")
   errorURL.SetPort(errorPort)
   if not errorURL.AsyncPostFromString(errorStr$) then stop

    unexpectedUrlErrorCount = 0

    while true

        msg = wait(10000, errorPort)   ' wait for either a timeout (10 seconds) or a message indicating that the post was complete

        if type(msg) = "rotINT32" then
            m.diagnostics.PrintDebug("### timeout before final error posted")
            ' clear
           a=RebootSystem()
            stop
        else if type(msg) = "roUrlEvent" then
           if msg.GetSourceIdentity() = errorURL.GetIdentity() then
              if msg.GetResponseCode() = 200 then
                    ' clear
                   a=RebootSystem()
                endif
            endif
        endif

        m.diagnostics.PrintDebug("### unexpected url event while waiting to reboot")
        unexpectedUrlErrorCount = unexpectedUrlErrorCount + 1
        if unexpectedUrlErrorCount > 10 then
            m.diagnostics.PrintDebug("### reboot due to too many url events while waiting to reboot")
            ' clear
            a=RebootSystem()
        endif

    endwhile

    return

End Sub




Please help, any ideas.
 
RokuLyndon

Re: Simple File Networking (update from any web server)

Mon Jun 14, 2010 9:53 am

on the flash card, what's in the log.txt file? It should have errors.

Who is online

Users browsing this forum: No registered users and 2 guests